| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import { defineStore } from 'pinia'
- import { ConstantStore } from '@/enum/store'
- import { ref, computed, onMounted, watch, reactive, watchEffect } from 'vue'
- import RootRouter from '@/router'
- import { useLocalStorageState } from 'vue-hooks-plus'
- import { AppRouter as AppRouterEnum, Emitter } from '@/enum'
- import { useEmitter } from '@/hooks/index'
- import { useRoute } from 'vue-router'
- /**
- * 1. 获取当前路由path
- * 2. 从缓存中获取router, 防止刷新都丢失状态
- * 3. 获取navbar路由list
- * 3.1 根据当前的路由path 反推到最顶级父元素 将其置为常亮
- * 4. 每次点击navbar的路由的时候,将对应的sider第一项展开
- */
- const emitter = useEmitter()
- const initAppRouterState: Router.RouterRecords = {
- navbar: {
- route: [],
- selectPath: ''
- },
- sider: {
- route: [],
- selectPath: '',
- openKeys: []
- }
- }
- export const useAppRouter = defineStore(ConstantStore.ROUTER, () => {
- let appRouter = reactive<Router.RouterRecords>(initAppRouterState)
- const route = useRoute()
- const [appRouterState, setAppRouterState] = useLocalStorageState<Router.RouterRecords>(AppRouterEnum.ROUTER, {
- defaultValue: initAppRouterState
- })
- const siderRoutes = computed(() => RootRouter.getRoutes().find(item => item.path === appRouter.navbar!.selectPath)?.children)
- const initAppRouter = () => {
- appRouter.navbar.route = RootRouter.options.routes.map(route => {
- return {
- path: route.path,
- name: route.name
- }
- })
- appRouter.navbar.selectPath = RootRouter.options.routes[0].path
- appRouter.sider.route = siderRoutes.value!
- setAppRouterState(appRouter)
- }
- const changeNavbar = (path: string) => {
- RootRouter.push(path)
- appRouter.navbar.selectPath = path
- }
- watch(
- () => RootRouter.currentRoute.value.path,
- () => {
- appRouter.sider = {
- route: RootRouter.getRoutes().find(item => item.path === appRouter.navbar!.selectPath)?.children as Router.RoutesProps[],
- selectPath: RootRouter.currentRoute.value.path,
- openKeys: [RootRouter.currentRoute.value.matched[1].path]
- }
- setAppRouterState(appRouter)
- emitter.emit(Emitter.NAVBAR)
- }
- )
- appRouter = appRouterState.value as Router.RouterRecords
- if (appRouter.navbar.route.length === 0) {
- initAppRouter()
- }
- return {
- router: appRouter,
- changeNavbar
- }
- })
|