permission.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import router from './router'
  2. import NProgress from 'nprogress' // 引入进度条
  3. import 'nprogress/nprogress.css' // 进度条样式
  4. import { appStore } from '_p/index/store/modules/app'
  5. import wsCache from '@/cache'
  6. import getPageTitle from '@/utils/get-page-title'
  7. NProgress.configure({ showSpinner: false }) // NProgress configuration
  8. import { permissionStore } from '_p/index/store/modules/permission'
  9. import type { RouteRecordRaw } from 'vue-router'
  10. const whiteList: string[] = ['/login'] // 不重定向白名单
  11. router.beforeEach((to, from, next) => {
  12. if (wsCache.get(appStore.userInfo)) {
  13. if (to.path === '/login') {
  14. next({ path: '/' })
  15. } else {
  16. if (permissionStore.isAddRouters) {
  17. next()
  18. return
  19. }
  20. permissionStore.GenerateRoutes().then(() => {
  21. permissionStore.addRouters.forEach(async(route: RouteRecordRaw) => {
  22. await router.addRoute(route.name!, route) // 动态添加可访问路由表
  23. })
  24. const redirectPath = (from.query.redirect || to.path) as string
  25. const redirect = decodeURIComponent(redirectPath)
  26. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
  27. permissionStore.SetIsAddRouters(true)
  28. next(nextData)
  29. })
  30. }
  31. } else {
  32. if (whiteList.indexOf(to.path) !== -1) {
  33. next()
  34. } else {
  35. // 否则全部重定向到登录页
  36. next({
  37. path: '/login',
  38. query: {
  39. redirect: to.path
  40. }
  41. })
  42. }
  43. }
  44. })
  45. router.afterEach((to) => {
  46. document.title = getPageTitle(to.meta.title, appStore.title)
  47. NProgress.done() // 结束进度条
  48. })