使用vue-router中的addRoutes踩坑记录

添加动态路由后刷新白屏/刷新进入404页面

近日在写项目时需要用到vue-router中的addRoutes来动态添加路由。
化简后代码如下

// 文件:router.js

import router from './router'

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()
  const hasGetUserInfo = store.getters.userInfo
  if (hasToken && hasGetUserInfo) {
    if (router.options.isAddDynamicMenuRoutes) {
      router.options.isAddDynamicMenuRoutes = false
      next()
    } else {
      store.dispatch('user/getMenu').then(res => {
        const dynamicRoutes = formatRoutes(res, true) // 格式化菜单数据并生成动态路由配置
        const routes = Object.values(dynamicRoutes)
        const integralRoutes = constantRoutes.concat(routes)
        router.options.routes = integralRoutes
        router.addRoutes([...routes])
        router.options.isAddDynamicMenuRoutes = true
        next({ ...to })
      }).catch(err => {
        console.log(err)
        next()
      })
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      store.dispatch('user/logout')
      next(`/login?redirect=${to.path}`)
    }
  }
})

{ path: ‘*’, redirect: ‘/404’, hidden: true }

上述代码添加后发现能正确的进入动态路由,也可以才正常切换,但是刷新后页面直接进去/404。

打断点调试后发现在刷新后beforeEach中的to中的信息直接指向'/404'

因为vue-router是存在内存中的,刷新后动态路由会消失,刷新后查询不到动态加载的页面,这显然与我预想的有出入,我希望在页面刷新后失去动态路由时,不重定向导向/404,需要将router.js文件中的{ path: '*', redirect: '/404', hidden: true }也添加为动态路由。

//router.js

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: 'Dashboard', icon: 'dashboard' }
    }]
  },

  //去掉找不到页面重定向/404
  { path: '*', redirect: '/404', hidden: true }
]

然后在添加动态路由时动态添加{ path: '*', redirect: '/404', hidden: true },此时,当页面刷新后找不到动态路由也不会重定向到/404页面,而是等待路由动态添加。

  router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])

总结

在使用addRoutes时,固定路由中不要设置{ path: '*', redirect: '/404', hidden: true },可以将{ path: '*', redirect: '/404', hidden: true }添加到动态路由中使用。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐