permission.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import router from './router'
  2. import { useAppStoreWithOut } from '@/store/modules/app'
  3. import { useCache } from '@/hooks/web/useCache'
  4. import type { RouteRecordRaw } from 'vue-router'
  5. import { useTitle } from '@/hooks/web/useTitle'
  6. import { useNProgress } from '@/hooks/web/useNProgress'
  7. import { usePermissionStoreWithOut } from '@/store/modules/permission'
  8. import { useDictStoreWithOut } from '@/store/modules/dict'
  9. import { usePageLoading } from '@/hooks/web/usePageLoading'
  10. import { getDictApi } from '@/api/common'
  11. const permissionStore = usePermissionStoreWithOut()
  12. const appStore = useAppStoreWithOut()
  13. const dictStore = useDictStoreWithOut()
  14. const { wsCache } = useCache()
  15. const { start, done } = useNProgress()
  16. const { loadStart, loadDone } = usePageLoading()
  17. const whiteList = ['/login'] // 不重定向白名单
  18. router.beforeEach(async (to, from, next) => {
  19. start()
  20. loadStart()
  21. if (wsCache.get(appStore.getUserInfo)) {
  22. if (to.path === '/login') {
  23. next({ path: '/' })
  24. } else {
  25. if (permissionStore.getIsAddRouters) {
  26. next()
  27. return
  28. }
  29. if (!dictStore.getIsSetDict) {
  30. // 获取所有字典
  31. const res = await getDictApi()
  32. if (res) {
  33. dictStore.setDictObj(res.data)
  34. dictStore.setIsSetDict(true)
  35. }
  36. }
  37. // 开发者可根据实际情况进行修改
  38. const roleRouters = wsCache.get('roleRouters') || []
  39. const userInfo = wsCache.get(appStore.getUserInfo)
  40. userInfo.role === 'admin'
  41. ? await permissionStore.generateRoutes('admin', roleRouters as AppCustomRouteRecordRaw[])
  42. : await permissionStore.generateRoutes('test', roleRouters as string[])
  43. permissionStore.getAddRouters.forEach((route) => {
  44. router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  45. })
  46. const redirectPath = from.query.redirect || to.path
  47. const redirect = decodeURIComponent(redirectPath as string)
  48. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
  49. permissionStore.setIsAddRouters(true)
  50. next(nextData)
  51. }
  52. } else {
  53. if (whiteList.indexOf(to.path) !== -1) {
  54. next()
  55. } else {
  56. next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
  57. }
  58. }
  59. })
  60. router.afterEach((to) => {
  61. useTitle(to?.meta?.title as string)
  62. done() // 结束Progress
  63. loadDone()
  64. })