doubleyong
管理员
管理员
  • 最后登录2026-05-25
  • 发帖数1198
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:7317回复:0

[vue]vue-router使用addRouter动态路由提示警告

楼主#
更多 发布于:2019-05-30 16:29
vue-router使用addRoutes做动态权限管理,如下:

this.$router.options.routes[1].children=[...subRoutes];
this.$router.addRoutes(this.$router.options.routes);


出现警告:
[vue-router] Duplicate named routes definition:


原因:因为有默认的动态路由,在执行addRoutes方法时,默认路由会在调用一次,这时就会提示重复。


在网上找到了很多的方法,终于被我找到了解决方案
参考如下地址:https://github.com/vuejs/vue-router/issues/1727

解决方案:
1. 在router/index.js , 在文件中添加 一个$addRoutes的方法
var router = new Router({
  routes: [
    {
      path: '*',
      name: '404',
      component: () => import('@/components/Page404'),  // 路由懒加载
    },
    {
      path:'/home',
      name:"Home",
      // meta: {requireAuth: true},
      component: (resolve)=> require(['@/components/Home'],resolve)
    },
    {
      path: '/login',
      name: 'Login',
      component: (resolve)=> require(['@/components/Login'],resolve)
    }
  ],
  mode:"history"
})
router.$addRoutes = (params) => {
  router.matcher = new Router({mode: 'history'}).matcher;
  router.addRoutes(params)
}
//路由前置守卫,权限判断
// 判断对应路由是否登录,保证有些组件的显示,必须是登录状态
router.beforeEach(function (to, from, next) {
  if (to.name === 'Login') {
    next();
  } else {
    if (to.meta.requireAuth) { // 验证用户是否登录
      if (sessionStorage.getItem('isLogin')) {
        next()
      } else {
        next({
          path: '/login'
        })
      }
    } else {
      next();
    }
  }
})
export default router;
2. 在动态添加路由的地方,使用如下代码:
this.$router.options.routes[1].children=[...subRoutes];
this.$router.$addRoutes(this.$router.options.routes);
这样就OK了
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号