vue-router 根據權限動態設置路由 theme.js" as it exceeds the max of "500KB".


需求: 根據不同角色的登錄人,展示不同的功能模塊. 前端路由在后台維護,動態注冊路由.  

業務流程:
  首先,登錄成功,獲取token
  其次,處理數據格式,主要是component的格式是,例如: import(`@view/user/${item.path}`)
  最后,通過this.addroutes()注冊動態路由  
關鍵技術   addRoutes:     解釋:動態注冊路由,router是在vue實例化的時候就已經注冊掛載,所以,官方提供了一個動態的注冊的api.     使用方法1:this.$router.addRoues = ([{title: '人員管理', path: 'name}])     使用方法2:         const router = new VueRouter();         router.addRoutes(); 坑:   1.component必須是函數,且不能使用字符拼接的方式生成組件路徑.     如:         標准:component: () => import('@view/user.vue');         錯誤:component: '@view/user.vue';         錯誤:component: () => import('@view/${item.path}');   2.不能存儲在localStorege等瀏覽器緩存內,會修改component的數據格式     如:存的時候是 component: () => import('@view/user.vue');         取時變成:component: xxxxx   3.需要在全局的"前置路由攔截"獲取"角色模塊",同時避免路由進入死循環. 前端路由對照表 reouterReference.js const routerReference = {     // 根據p路由path格式化component     'workshop': () => import('@/views/workshop/index.vue'),     'path': () => import('@/views/user/index.vue'), } expport default routerReference; getRoleModuleList.js //從服務器獲取路由,格式化component axios('module/list',{}, {authorToken: '123123123'}) .then(res) => {     if (res.data.status === 200) {         this.moduleLsit = res.data.res;         this.moduleList.map(item => {             item.component = reouterReference(route.path);// 創建component             return item;              })     }; } 注: 此處省略遞歸處理數據邏輯 router.beforeEach((to, from, next) => {     addRouterArr = store.state.addRouterList;     // 已登錄     if (Cookies.get('token')) { // 未登錄且前往的頁面不是登錄頁         // 已經登錄且前往的是登錄頁         if (Cookies.get('user') && to.name === 'login') {             Util.title();             next({                 name: 'home_index'             });         } else {             // 角色對應的模塊存在的情況下             if (addRouterArr && addRouterArr.length !== 0) {                 // 緩存打開的路由                 localStorage.setItem('activeRouteName', JSON.stringify({                     name: to.name,                     query: to.query,                     params: to.params                 }));                 next();             } else {                 // 獲取角色對應的模塊                 getRoleModuleList(to, next);             };             // next();         }         iView.LoadingBar.finish();     } else if (!Cookies.get('token')) {         if (to.name === 'login') {             next();         } else {             next({                 name: 'login'             });         };         // 未登錄         iView.LoadingBar.finish();     } });

  


免責聲明!

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



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