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();
}
});