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

需求: 根據不一樣角色的登陸人,展現不一樣的功能模塊. 前端路由在後臺維護,動態註冊路由.  javascript

業務流程:
  首先,登陸成功,獲取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();
    }

});
相關文章
相關標籤/搜索