- 开发一个不同用户不同权限显示不同菜单项目 , 需要实现不同权限添加不同路由
- 通过前置路由守卫
router.beforeEach
实现
- 二级菜单路由列表
const childRouters = {
"/good": {
path: "/good",
name: "Good",
component: () =>
import(/* webpackChunkName: "good" */ "../views/Good/Good.vue"),
},
"/category": {
path: "/category",
name: "Category",
component: () =>
import(
/* webpackChunkName: "category" */ "../views/Category/Category.vue"
),
},
"/brand": {
path: "/brand",
name: "Brand",
component: () =>
import(/* webpackChunkName: "brand" */ "../views/Brand/Brand.vue"),
},
"/attribute": {
path: "/attribute",
name: "Attribute",
component: () =>
import(
/* webpackChunkName: "attribute" */ "../views/Attribute/Attribute.vue"
),
},
"/order": {
path: "/order",
name: "Order",
component: () =>
import(/* webpackChunkName: "order" */ "../views/Order/Order.vue"),
},
"/topic": {
path: "/topic",
name: "Topic",
component: () =>
import(/* webpackChunkName: "topic" */ "../views/Topic/Topic.vue"),
},
"/statdata": {
path: "/statdata",
name: "Statdata",
component: () =>
import(
/* webpackChunkName: "statdata" */ "../views/Statdata/Statdata.vue"
),
},
};
const genRoute = () => {
let newRouters = [];
for (let i = 0; i < store.state.powerList.length; i++) {
var path = store.state.powerList[i].path;
if (childRouters[path]) {
newRouters.push(childRouters[path]);
}
}
router.addRoutes([
{
path : '/home',
component:() => import(/* webpackChunkName: "home" */ '../views/Home/Home.vue'),
children : newRouters
}
])
};
router.beforeEach((to, form, next) => {
// 当没有本地token , 并且目标路由不是login时执行
if (to.path !== "/login" && !localStorage.getItem("token")) {
return next("/login");
// 当有token 没有数据时执行
} else if (store.state.powerList.length === 0 && localStorage.getItem("token")) {
GetUserByToken().then((response) => {
store.commit("savePowerList", response.data.menu );
genRoute();
return next( store.state.powerList[0].path );
});
} else {
next();
}
});
网友评论