在Vue3中使用router.addRoute动态添加路由时,由于路由添加是异步的,第一次不会匹配到未添加的路由导致告诫,先把404写在固定路由内里,用来捕获第一次未匹配到的路由,就不会有告诫了,但是会出现一革新就跳转404
- {
- path: '/404',
- name: '404',
- component: () => import('@/views/error/404.vue'),
- hidden: true,
- meta: { title: "找不到此页面" }
- },
- {
- path: '/:pathMatch(.*)',
- name: 'notFound',
- hidden: true,
- redirect: '/404',
- },
复制代码 所以在router.beforeEach内里必要判断一下,userPermissionsStore是使用了pinia存routes
- try {
- const permissionsState = userPermissionsStore()
- // 判断是否添加成功
- // permissionsState.routes的数据在permissionsState.getRoutes()中设置
- if (!permissionsState.routes.length) {
- // 获取要加载的路由
- const accessRoutes = await permissionsState.getRoutes()
- accessRoutes.forEach((item) => router.addRoute(item))
-
- // 这里是核心代码,因为第一次匹配不到会跳转404
- // 所以跳转到404的时候再做一个操作
- if (to.path == '/404' && to.redirectedFrom) {
- next({ path: to.redirectedFrom.fullPath, replace: true })
- } else {
- next({ ...to, replace: true }) // 这里相当于push到一个页面 不在进入路由拦截
- }
- } else {
- next() // 如果不传参数就会重新执行路由拦截,重新进到这里
- }
- } catch (err) {
- next(`/login?redirect=${to.path}`)
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |