不容错过,原生js实现类似vue路由守卫效果

js原生模拟路由守卫

 window.addEventListener('popstate', function listener() {
    // commonUtils是我这项目的公共方法存储的文件

            commonUtils

                .showConfirmDialog('您确定要返回吗?订单信息已生成,您可在倒计时结束前,在“我的健康”->“我的课程”列表中查看')

                .then(() => {

                    commonUtils.gotoHome();

                    console.log('1');

                })

                .catch(() => {

                    window.history.pushState(null, '', document.URL);

                })

                .finally(() => commonUtils.hideLoading());

        });

        console.log(document.URL);

vue路由守卫写法 

      
import { onBeforeRouteLeave } from 'vue-router';

onBeforeRouteLeave((to) => {

            if (to.path === '/health-knowledge/course-pay-infomation') {

                commonUtils

                    .showConfirmDialog('您确定要返回吗?订单信息已生成,您可在倒计时结束前,在“我的健康”->“我的课程”列表中查看')

                    .then(() => {

                        commonUtils.gotoHome();

                    })

                    .catch(() => {

                        window.history.go(1);

                    })

                    .finally(() => commonUtils.hideLoading());

            }

        });

猜你喜欢

转载自blog.csdn.net/aZHANGJIANZHENa/article/details/125757292
今日推荐