|
|
|
import router from '@/router'
|
|
|
|
import pinia from './store'
|
|
|
|
import useUserStore from '@/store/modules/user'
|
|
|
|
import permissionStore from '@/store/modules/permission'
|
|
|
|
|
|
|
|
//@ts-expect-error 修复ts校验
|
|
|
|
import nprogress from 'nprogress'
|
|
|
|
import 'nprogress/nprogress.css'
|
|
|
|
const userStore :any = useUserStore(pinia)
|
|
|
|
const usePermissionStore = permissionStore(pinia)
|
|
|
|
// const whitelist = ['/login', '/404']
|
|
|
|
router.beforeEach(async (to, form, next) => {
|
|
|
|
// 进度条开始\
|
|
|
|
nprogress.configure({ showSpinner: false })
|
|
|
|
nprogress.start()
|
|
|
|
// 判断是否登录
|
|
|
|
if (userStore.token) {
|
|
|
|
// 登录成功访问登录页则跳转到首页
|
|
|
|
if (to.path == '/login') {
|
|
|
|
next({ path: '/' })
|
|
|
|
} else {
|
|
|
|
// 登录成功判断是否获取到了用户信息
|
|
|
|
if (userStore.userName) {
|
|
|
|
next()
|
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
// 没有获取到用户信息 就获取用户信息 然后放行
|
|
|
|
await userStore.getUserInfo()
|
|
|
|
// 获取筛选到的路由
|
|
|
|
const asyncRouter = await usePermissionStore.getAsyncRoutes(
|
|
|
|
userStore.routes,
|
|
|
|
)
|
|
|
|
// 遍历筛选出来的路由通过addRoute添加到路由表
|
|
|
|
asyncRouter.forEach((item: any) => {
|
|
|
|
router.addRoute(item)
|
|
|
|
})
|
|
|
|
// 在最后向路由表添加一个404规则
|
|
|
|
// 切记不要写到路由表内 否者刷新页面会跳转到404页面
|
|
|
|
router.addRoute({
|
|
|
|
path: '/:pathMatch(.*)*',
|
|
|
|
component: () => import('@/views/404/index.vue'),
|
|
|
|
name: 'Any',
|
|
|
|
meta: {
|
|
|
|
title: '任意',
|
|
|
|
hidden: true,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
next({ ...to, replace: true }) // 这里相当于push到一个页面 不在进入路由拦截
|
|
|
|
} catch (error) {
|
|
|
|
// 如果获取用户信息失败了则执行登出操作让重新登录
|
|
|
|
console.log(error)
|
|
|
|
userStore.logout()
|
|
|
|
next({ path: '/login' })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// 没有token访问登录页放行
|
|
|
|
if (to.path == '/login') {
|
|
|
|
next()
|
|
|
|
} else {
|
|
|
|
// 访问其他页面则阻止
|
|
|
|
next({ path: '/login', query: { redirect: to.path } })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
// router.beforeEach((to, form, next) => {
|
|
|
|
// console.log(to, 'to')
|
|
|
|
// next()
|
|
|
|
// })
|
|
|
|
router.afterEach(() => {
|
|
|
|
nprogress.done()
|
|
|
|
})
|
|
|
|
export default router
|