https://router.vuejs.org/zh/api/#router-addroutes
//登录成功 -> 后端给出该用户的页面规则
// url -> 文件路径
menu: [
{
path: '/',
name: 'home',
label: '首页',
icon: 's-home',
url: 'Home/Home'
},
{
path: '/user',
name: 'user',
label: '用户管理页',
icon: 'user',
url: 'UserManage/UserManage'
},
{
label: '其他',
icon: 'location',
children: [
{
path: '/page1',
name: 'page1',
label: '页面1',
icon: 'setting',
url: 'Other/PageOne'
},
{
path: '/page2',
name: 'page2',
label: '页面2',
icon: 'setting',
url: 'Other/PageTwo'
}
]
}
],
//router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: () => import('@/views/Login/login')
}
]
const router = new VueRouter({
routes
})
export default router
// 添加菜单
addMenu(state, router) {
//登录接口只会请求一次,为避免页面刷新丢失上面的路由规则,应该本地保存
//{ ... }
let currentMenu = [
//默认配置根路由,例如layout等模板页面,此为Main.vue
{
path: '/',
component: () => import(`@/views/Main`),
children: []
}
]
// 遍历后端给的路由规则,与默认配置进行封装合并
menu.forEach(item => {
if (item.children) {
item.children = item.children.map(item => {
item.component = () => import(`@/views/${item.url}`)
return item
//{
// path: '/page1',
// name: 'page1',
// label: '页面1',
// icon: 'setting',
// url: 'Other/PageOne',
// component : () => import(`@/views/Other/PageOne`)
// },
})
// 添加动态路由
currentMenu[0].children.push(...item.children)
} else {
item.component = () => import(`@/views/${item.url}`)
currentMenu[0].children.push(item)
}
})
console.log(currentMenu, 'cur')
// 添加该用户路由规则
router.addRoutes(currentMenu)
},