需求:增加权限控制,实现不同角色显示不同的路由导航
思路:每次登陆后请求接口返回当前角色路由
核心方法:vue-router2.2.0的addRoutes方法 + vuex
以下是我实现的获取菜单路由的方法,我将该方法的调用放在首页组件的生命钩子中,即便用户刷新浏览器清空了路由还是会重新调用接口获取,不至于会丢失。同时考虑到会有切换用户的可能,所以不将获取到的路由信息保存到cookie或者localstorage当中
获取菜单之前先判断routerState,避免多次请求, 我这里使用element-ui的导航菜单功能v-for循环this.myRouter参数即可显示动态路由导航
getMenu () {
if (this.$store.getters.routerState === false) {
// 清理已经存在的动态路由
this.clearDynamicRoute()
// 更改请求路由状态为true
this.$store.commit('SET_ROUTERSTATE', true)
getMyMenu().then((res) => {
if (res.code === '0') {
// 格式化路由,将数据转为addRoutes可接受的route格式数组
let myMenu = this.formatMenu(res.data.menu)
if (myMenu.length <= 0) { // 没有动态路由
return
}
for (let index = 0; index < myMenu.length; index++) {
// 将请求的路由先存放到options对象中
this.$router.options.routes.push(myMenu[index])
}
// 将完整需要显示的路由添加进去
this.$router.addRoutes(this.$router.options.routes)
// 这里将路由显示在页面上
this.MyRouter = this.$router.options.routes
}
// 在这里就可以打印出新路由
console.log(this.$router)
})
}
}
补充知识:vue+element 进入不同路由页面(二级页面),让相应的左侧菜单
路由配置
{
path: '/finance',
name: 'Finance',
meta: {
title: '财务'
},
component: () =>
import('@/components/Finance'),
redirect: '/finance/code/code',
children: [{
path: '/finance/code',
name: 'financeindex',
meta: {
title: '税收配置'
},
redirect: '/finance/code/code',
component: () =>
import('@/components/finance/financeindex'),
children: [{
path: '/finance/code/code',
name: 'FinanceCode',
hidden: false,
active:'/finance/code', //这里是在左侧菜单显示并且需要选中的
meta: {
title: '税收编码(金税)'
},
component: () =>
import('@/components/finance/code/Code'),
},
{
path: '/finance/code/codeimportrecord', // 这个路由进入的界面是 税收编码(金税)的二级页面, 当进入这个页面的时候,需要菜单中的税收编码(金税)显示选中
name: 'FinanceCodeimportRecord',
hidden: true,
meta: {
title: '税收编码导入记录'
},
component: () =>
import('@/components/finance/code/CodeimportRecord'),
},
{
path: '/finance/classcode/classcode',
name: 'FinanceClassCode',
hidden: false,
active:'/finance/classcode', //为了省事,只给需要在左侧显示的路由添加active属性
meta: {
title: '分类税收编码确认'
},
component: () =>
import('@/components/finance/classCode/ClassCode'),
},
]
}, ]
element
{{nav.meta.title}} {{item.meta.title}}


