[轉]vue-router動態添加路由的方法,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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM