import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {routePage,asynRouter} from './router.list'
import util from '_m/util'
import store from '../store'
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
mode: 'history',
linkActiveClass: 'active',
routes: routePage
})
const whiteList = ['/login','/resetPwd','/register']
//路由守卫
router.beforeEach((to, from, next) => {
NProgress.start()
if (util.getCookie('Admin-Token')) {
if (to.path === '/login') {
next({ path: '/index' })
NProgress.done()
} else {
if (store.getters.get_roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息
store.dispatch('GetUser')
store.dispatch('GetConfig').then(res => {
if(res) {
router.addRoutes(asynRouter) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
}
}).catch(err => {
util.delCookie('Admin-Token')
next({ path: '/' })
})
} else {
next()
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next()
} else {
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
export default router
vue 前端路由拦截器实现代码
最新推荐文章于 2024-01-30 16:05:46 发布