vue3中在router/index.js中
import { createRouter, createWebHistory } from 'vue-router';
import store from 'store'
const userRule = {
path: 'user',
component: () => import('@/views/user/index.vue'),
children: [
{
path: 'list',
name: 'userList',
meta: { title: '用户列表', parents: '用户管理', keepAlive: true },
component: () => import('@/views/user/userList.vue'),
},
{
path: 'list',
name: 'userList',
meta: { title: '用户列表', parents: '用户管理', keepAlive: true },
component: () => import('@/views/user/userList.vue'),
}
]
}
const operationRule = {
path: 'opreation',
component: () => import('views/opreation/index.vue'),
}
const reviewRule = {
path: 'review',
component: () => import('views/review/index.vue'),
}
const addissuanceRule = {
path: 'addissuance',
component: () => import('views/addissuance/index.vue'),
}
const financeRule = {
path: 'finance',
component: () => import('views/finance/index'),
}
const statisticsRule = {
path: 'statistics',
component: () => import('views/statistics/index'),
}
const accountRule = {
path: 'account',
component: () => import('views/account/index'),
};
const ruleMapping = {
'user': userRule,
'review': reviewRule,
'operation': operationRule,
'addissuance': addissuanceRule,
'finance': financeRule,
'statistics': statisticsRule,
'account': accountRule,
}
const routes = [
{
path: "/",
name:'home',
meta:{title:'首页'},
component: () => import('views/Home.vue'),
},
{
path: '/login',
component: () => import('views/Login.vue')
},
{
path: "/:catchAll(.*)",
component: () => import('views/404.vue')
}
]
const router = createRouter({
history: createWebHistory(),
routes: routes
})
export function initDynamicRoutes() {
const currentRoutes = router.options.routes;
const menuList = store.state.user.menuList;
const rights = store.state.user.userInfo.rights;
menuList.forEach(item => {
if(item.authority.includes(rights)){
const temp = ruleMapping[item.name];
router.addRoute('home',temp)
}
})
}
let routerFlag = true;
router.beforeEach((to, from, next) => {
document.title = to.meta.title
let userInfo = store.getters['user/users'];
if (!userInfo && to.path != '/login') {
next('/login')
} else {
if(routerFlag){
initDynamicRoutes();
console.log(routerFlag);
next({path:to.path})
routerFlag = false;
}else{
next();
}
}
})
export default router;
vue2 中动态添加路由
export function initDynamicRoutes(){
console.log(router);
const currentRoutes = router.options.routes;
const rightList = store.state.rightList;
rightList.forEach( item => {
item.children.forEach(item =>{
const temp = ruleMapping[item.path];
temp.meta = item.rights
currentRoutes[2].children.push(temp);
})
})
router.addRoutes(currentRoutes);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步