Vue 添加動態路由路徑重復+刷新頁面丟失問題


今天在做一個后端動態路由頁面,有公共頁面和權限頁面,權限有學生權限和教師權限,遇到了動態添加路由的問題。

在動態添加學生或者教師頁面的時候,調用addRoutes

router.addRoutes(teacherRouter);

1.添加完動態路由后第一個問題 是:切換路由時,vue會警告路由名字重復,如下圖:

 

問題出現原因是:動態路由添加時調佣addRoutes();它只會幫你注入路由,不會幫你把前面的路由清掉。如此一來就重復添加了。

 

第一個問題 解決方法:路由動態添加關鍵頁面需要在路由配置頁(router/index.js)添加自定義方法

router.$addRoutes = params => {
  router.matcher = new Router({
    routes: router.options.routes
  // 關鍵代碼
  }).matcher;
  router.addRoutes(params);
};

 

2. 問題:在添加后進行頁面刷新后,動態添加的路由會消失,路勁找不到

可以使用localstorage緩存,頁面路由權限判斷頁(promission.js)用了路由beforeEach可以直接判斷路由刷新:

代碼如下:

  if (from.name === null) {
      // 刷新
      router.$addRoutes(accessRoutes);
      // 確保頁面加載完成
      next({ ...to, replace: true });
  }    

 

 3.問題:切換不同角色權限,之前動態添加的路由沒有被清除,進入看到的還是上次進入的權限頁面。

問題在於vue的store沒有被清空,把store里的route清空就行:

可以在退出登錄設置,也可以在添加路由時清空,以下代碼為store內permission.js添加動態路由前清空路由

代碼:

 

 1 const mutations = {
 2   SET_ROUTES: (state, routes) => {
 3     state.addRoutes = routes;
 4     state.routes = constantRoutes.concat(routes);
 5   },
 6   RESET_ROUTES: (state, payLoad) => {
 7     state.addRoutes = [];
 8     state.routes = [];
 9   }
10 };  
 1 generateRoutes({ commit }, roles) {
 2     return new Promise(resolve => {
 3       // 關鍵代碼 == 添加路由前將路由重置為空
 4       commit("RESET_ROUTES");
 5       // 設置登錄的路由權限
 6       let accessedRoutes;
 7    
 8      if (roles === 4) {
 9         // 教師登錄
10         accessedRoutes = teacherRouter;
11       }
12       if (roles === 3) {
13         // 學生登錄
14         accessedRoutes = studentRouter;
15       }
16 
17       commit("SET_ROUTES", accessedRoutes);
18       resolve(accessedRoutes);
19     }); 

 

 參考鏈接:https://www.cnblogs.com/imjtzhang/p/13709166.html

 

 


免責聲明!

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



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