1. 程式人生 > 其它 >[轉]vue-router動態新增路由的方法,addRouter新增路由,提示:Duplicate named routes definition

[轉]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