• [转]vuerouter动态添加路由的方法,addRouter添加路由,提示:Duplicate named routes definition


    问题描述:在做使用vue-router动态添加路由的方法,addRouter添加,使用

    console.log(this.$router.options.routes)

    打印对象,发现添加成功,但是一直提示:Duplicate named routes definition
    错误原因:路由中有重复的名称。

    添加路由的方法,代码如下:

    function createRouter(arr){
      let subRoutes=[];
      arr.forEach((item)=>{
        if (config.componentList.get(item.pathname) == "") {
          subRoutes.push({
            path: item.menuUrl,
            name: item.pathname,
            meta: {requireAuth: true,menuId:item.menuId}
          })
        } else {
          let component = config.componentList.get(item.pathname);
          subRoutes.push({
            path: item.menuUrl,
            name: item.pathname,
            meta: {requireAuth: true,menuId:item.menuId},
            component: resolve => require(["@/components/" + component + ""], resolve)
          })
        }
      });
      return subRoutes;
    }
    // 执行动态添加路由
    function DynamicAddRouter(){
      let subRoutes=[];
      subRoutes = createRouter(store.getters.getMenuInfo);
      store.getters.getMenuInfo.forEach((item)=>{
        if(item.menuChilds.length && item.menuChilds.length>0){
          subRoutes.push(...createRouter(item.menuChilds));
        }
      });
      router.options.routes[0].children=[...subRoutes];
      router.options.routes.push(
      {
        path:'*',
          name:"404",
        component: (resolve)=> require(['@/components/Page404'],resolve)
      });
      console.log(router.options.routes);
      router.addRoutes(router.options.routes);
    }

    解决方法:自己定义一个$addRoutes的方法,在router/index.js下
    代码如下:

    router.$addRoutes = (params) => {
      router.matcher = new Router({mode: 'history'}).matcher;
      router.addRoutes(params)
    }

    然后在动态添加路由时,使用自定义的方法

    router.$addRoutes(router.options.routes);

    解析:

    addRoutes 方法仅仅是帮你注入新的路由,并没有帮你剔除其它路由!

    设想存在这么一种情况:用户在自己电脑上登录了管理员账号,这个时候会向路由中注入管理员的路由,然后再退出登录,保持页面不刷新,改用普通用户账号进行登录,这个时候又会向路由中注入普通用户的路由,那么,在路由中将存在两种用户类型的路由,即使用户不感知,通过改变 url,普通用户也可以访问管理员的页面!

    对于这个问题,也有一个解决办法

    通过新建一个全新的 Router,然后将新的 Router.matcher 赋给当前页面的管理 Router,以达到更新路由配置的目的。自定义的$addRoutes,就是实现这个功能
    参考 :https://blog.csdn.net/suolong914/article/details/89432563

    原文链接:vue-router动态添加路由的方法,addRouter添加路由,提示:Duplicate named routes definition

  • 相关阅读:
    SpringMVC自动封装List对象 —— 自定义参数解析器
    fetch封装
    基于jQuery实现简单的js模块化
    CSS实现树形结构 + js加载数据
    java多线程
    JS中AOP的实现和运用
    移动端通过ajax上传图片(文件)并在前台展示——通过H5的FormData对象
    chart.js使用常见问题
    用PHP和Ajax进行前后台数据交互——以用户登录为例
    用JS添加和删除class类名
  • 原文地址:https://www.cnblogs.com/rainbow70626/p/16093799.html
Copyright © 2020-2023  润新知