欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue路由守卫

程序员文章站 2022-03-24 18:24:57
...
import Vue from 'vue';
import Router from 'vue-router';
import regindex from '@/pages/register/regindex';
import userauthent from '@/pages/register/userauthent';
import submit from '@/pages/register/submit';
import error from '@/pages/error';

Vue.use(Router);

const router = new Router({
    routes: [{
            name: 'regindex',
            path: '/register/regindex',
            component: regindex
        },
        {
            name: 'userauthent',
            path: '/register/userauthent',
            component: userauthent
        },
        {
            name: 'submit',
            path: '/register/submit',
            component: submit
        },
        {
            name: 'error',
            path: '/error',
            component: error
        }
    ]
});

const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名单

router.beforeEach((to, from, next) => {
    console.log('进入守卫');

    const flag = true; //鉴权
    if (flag) {
        next();
    } else {
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
            next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
        } else {
            next({ path: '/register/regindex', replace: true, query: { noGoBack: true } })
        }
    }

});