router.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { defineStore } from 'pinia'
  2. import { ConstantStore } from '@/enum/store'
  3. import { reactive, watch } from 'vue'
  4. import RootRouter from '@/router'
  5. import VueRouter from 'vue-router'
  6. const initAppRouterState: ROUTER.RouterRecords = {
  7. navbar: {
  8. route: [],
  9. selectPath: []
  10. },
  11. sider: {
  12. route: [],
  13. selectPath: '',
  14. openKeys: []
  15. }
  16. }
  17. export const useAppRouter = defineStore(ConstantStore.ROUTER, () => {
  18. const appRouter = reactive<ROUTER.RouterRecords>(initAppRouterState)
  19. const initAppRouter = () => {
  20. appRouter.navbar.route = RootRouter.options.routes.map((route: any) => {
  21. return {
  22. path: route.link ? route.path.substr(1) : route.path,
  23. name: route.name,
  24. link: !!route.link,
  25. redirect: route.redirect || ''
  26. }
  27. }).filter(_ => _.path !== '/login')
  28. appRouter.sider.route = RootRouter.options.routes[1].children!
  29. }
  30. if (appRouter.navbar.route.length === 0) {
  31. initAppRouter()
  32. }
  33. const changeNavbarRoute = (route: ROUTER.RoutesProps) => {
  34. if (route.link) {
  35. window.open(route.path)
  36. } else {
  37. appRouter.navbar.selectPath = [route.path]
  38. RootRouter.push(route.path)
  39. }
  40. }
  41. watch(
  42. () => RootRouter.currentRoute,
  43. () => {
  44. console.log('RootRouter.currentRoute:', RootRouter.currentRoute)
  45. }
  46. )
  47. return {
  48. router: appRouter,
  49. changeNavbarRoute
  50. }
  51. })