first commit
This commit is contained in:
81
src/router/index.js
Normal file
81
src/router/index.js
Normal file
@@ -0,0 +1,81 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import cache from '@/utils/cache'
|
||||
import useUserStore from '@/store/modules/user'
|
||||
import usePermissionStore from '@/store/modules/permission'
|
||||
import debounce from 'lodash/debounce'
|
||||
|
||||
const whiteList = [ '/login', '/404' ]
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '',
|
||||
meta: {
|
||||
auth: false,
|
||||
title: '首页'
|
||||
},
|
||||
component: () => import('@/views/business/index.vue'),
|
||||
children: [
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
meta: {
|
||||
auth: false,
|
||||
title: '登录'
|
||||
},
|
||||
component: () => import('@/views/login/index.vue')
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
component: () => import('@/views/error/404.vue'),
|
||||
hidden: true
|
||||
}
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes
|
||||
})
|
||||
|
||||
router.beforeEach((to, from, next) => {
|
||||
const token = cache.local.get('token')
|
||||
if (token) {
|
||||
if (whiteList.indexOf(to.path) !== -1) {
|
||||
next()
|
||||
} else {
|
||||
if (useUserStore().roles.length === 0) {
|
||||
// 判断当前用户是否已拉取完user_info信息
|
||||
useUserStore().getInfo().then(() => {
|
||||
usePermissionStore().generateRoutes().then(accessRoutes => {
|
||||
accessRoutes.forEach(route => {
|
||||
router.addRoute(route) // 动态添加可访问路由表
|
||||
})
|
||||
|
||||
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
|
||||
})
|
||||
}).catch(err => {
|
||||
// 登出接口防抖操作
|
||||
debounce(() => {
|
||||
useUserStore().logout().then(() => {
|
||||
ElMessage.error(err)
|
||||
next({ path: '/login' })
|
||||
})
|
||||
}, 1000)()
|
||||
})
|
||||
} else {
|
||||
next()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 没有token
|
||||
if (whiteList.indexOf(to.path) !== -1) {
|
||||
// 在免登录白名单,直接进入
|
||||
next()
|
||||
} else {
|
||||
// next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
|
||||
next('/login') // 否则全部重定向到登录页
|
||||
}
|
||||
}
|
||||
})
|
||||
export default router
|
||||
Reference in New Issue
Block a user