vue3 某一级路由有3个子路由,点击切换到第三个子路由,然后切换其他的一级路由再切换到开始的一级路由,要求自动选中第三个子路由 如何实现?-灵析社区

sssssjkl

简单说一下思路就是使用 `pinia` 或者 `ls` 缓存一下之前的路由值,在一级路由的导航守卫的 `beforeEnter` 钩子里面做一下读取然后 `replace` 过去就好了 * * * ### Edit import { createRouter, createWebHistory } from 'vue-router' import RouterViewer from '../components/RouterViewer.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/page', name: 'app', component: RouterViewer, children: [ { path: '/page/home', name: 'home', component: () => import('../views/HomeView.vue'), }, { path: '/page/about', name: 'about', component: () => import('../views/AboutView.vue') } ] } ] }) router.beforeEach((to, from) => { console.log('-----------------------------------') console.log('to => ', { ...to }) console.log('from => ', { ...from }) // 获取当前路由匹配信息,并且反转,以便获取最近的目录菜单 const reverseMatchedList = to.matched.toReversed() // 这里用的 `toReversed()`,如果不兼容使用 `reverse()` 替换时会有修改源数组的问题,需要注意。 // 获取目录菜单下标 const catalogIndex = reverseMatchedList.findIndex(ro => ro.children.length) // 获取当前匹配目录的信息 const catalogData = reverseMatchedList[catalogIndex] // 当前是否是前往有子路由的目录,即下标为 0 if(catalogIndex === 0) { // 从本地缓存中获取目录缓存的子路由路径 let cachePath = localStorage.getItem(catalogData.path) // 重定向到缓存中的路径, 如果没有则重定向到第一个子路由 return cachePath || catalogData.children[0].path } else { // 如果不是前往有子路由的目录,则缓存当前路由路径,到目录缓存下。 localStorage.setItem(catalogData.path, to.fullPath) return true } }) export default router

阅读量:1

点赞量:0

问AI