asyncRouter.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 动态路由
  2. import { GlobalStore } from '@/stores/index'
  3. import router from '@/router/index'
  4. import { notFoundRouter } from './staticRouter'
  5. import { ElNotification } from 'element-plus'
  6. // 加载views下面所有的.vue文件
  7. const modules = import.meta.glob('@/views/**/*.vue')
  8. console.log(modules)
  9. export const asyncAddRouter = () => {
  10. const globalStore = GlobalStore()
  11. globalStore.GET_Flat_Menu.forEach((item: any) => {
  12. item.children && delete item.children
  13. if (item.component && typeof item.component == 'string') {
  14. // item.component = modules['/src/views' + item.component + '.vue']
  15. console.log(item)
  16. }
  17. if (item.meta.isFull) {
  18. router.addRoute(item)
  19. } else {
  20. router.addRoute('Index', item)
  21. }
  22. })
  23. }
  24. /**
  25. * 初始化动态路由
  26. */
  27. export const initDynamicRouter = async () => {
  28. const globalStore = GlobalStore()
  29. try {
  30. // 判断是否已经加载过路由了
  31. // 1.获取菜单列表 && 用户信息
  32. await globalStore.SET_UserInfo()
  33. await globalStore.SET_Menu_User_List()
  34. // 2.判断当前用户有没有菜单权限
  35. if (!globalStore.GET_Menu_List.length) {
  36. ElNotification({
  37. title: '无权限访问',
  38. message: '当前账号无任何菜单权限,请联系系统管理员!',
  39. type: 'warning',
  40. duration: 3000
  41. })
  42. globalStore.SET_User_Tokey('')
  43. globalStore.SET_User_Info({})
  44. router.replace('/login')
  45. return Promise.reject('No permission')
  46. }
  47. // 3.添加动态路由
  48. asyncAddRouter()
  49. // 4.最后添加 notFoundRouter
  50. router.addRoute(notFoundRouter)
  51. } catch (error) {
  52. // 💢 当按钮 || 菜单请求出错时,重定向到登陆页
  53. globalStore.SET_User_Tokey('')
  54. router.replace('/login')
  55. return Promise.reject(error)
  56. }
  57. }