vue-router 路由拦截 beforeEach 添加静态路由 与 动态添加路由

1。router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/page/login'
import Error from '../components/a/404'

import NProgress from 'nprogress'//加载进度条

import Main from '../components/a/main'

Vue.use(Router)

NProgress.inc(0.2)
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })


const staticRouter = [
    {
        path: '/',
        component: Login
    },
    {
        path: '/404',
        component: Error
    },
];

const createRouter = () => new Router({
    mode: 'history',
    routes : staticRouter
});

const router = createRouter();

const asyncRouterArr = [
    {
        path:'/main',
        component:Main,
    },
]

/**
 * 重定向不要添加到原始路由中,要不然都会重定向到某页面
 * 重定向在添加路由时,最后添加进去
 * */

router.beforeEach((to, from, next) => {
    NProgress.start();
    console.log(to, from);
    if(to.fullPath != '404'){
        let _this = router.app;
        //判断用户是否登录
        if(!_this.$store.state.isLogin){
            //已登录
            if(localStorage.getItem("token")){
                _this.$store.dispatch('getNavData').then((res)=>{
                    let navList =  _this.$store.state.navList;
                    navList.push({path:'*',redirect:'/404'});
                    _this.$router.options.routes= navList;
                    _this.$router.addRoutes(navList);
                    next(to.fullPath);
                })
            }else{
                if (to.path !== '/') {
                    next(from.fullPath)
                } else {
                    // next(from.fullPath)
                    next()
                }
            }

        }else{
            //判断vuex中state的navList是否有值,
            if(_this.$store.state.navList.length > 0){
                //有值的话,代表从后台获取到登录成功的路由权限,继续往下走
                next();
            }else{
                //没值的话,代表是浏览器手动刷新,vuex中的数据设为初始值
                _this.$store.dispatch('getNavData').then((res)=>{
                    let navList =  _this.$store.state.navList;
                    navList.push({path:'*',redirect:'/404'});
                    _this.$router.options.routes= navList;
                    _this.$router.addRoutes(navList);
                    next(to.fullPath);
                })
            }
        }
    }else{
        next();
    }

})

router.afterEach(()=>{
    NProgress.done();
});

export function resetRouter(){
    const newRouter = createRouter();
    router.matcher = newRouter.matcher; //reset router
}

export default router;

  

posted @ 2019-11-15 15:12  董七  阅读(4771)  评论(0编辑  收藏  举报