vue实现根据用户设置不同路由 路由的动态加载
dearweb 发布:2021-05-14 23:08:01阅读:在开发一个后台管理项目时会根据用户的不同设置不同的权限,这个时候我们就需要用到动态添加路由的方式进行,并结合前置路由守卫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(); }});
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧