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;
