权限控制的方法:
1.路由元信息(meta)
2.动态加载菜单和路由(addRoutes)
一、路由元信息
方式一:
钩子函数:
Vue.beforeEach(function(to,form,next){}) /*在跳转之前执行*/
Vue.afterEach(function(to,form)) /*在跳转之后判断*/
to:router即将进入的路由对象
from:当前导航即将离开的路由
next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
路由部分:
{
path: '/',
name: 'index',
meta: {
roles: ['admin', 'user']
},
component: () => import('../views/Index.vue')
},
{
path: '/about',
name: 'about',
meta: {
roles: ['admin']
},
main.js部分:
//假设有两种角色:admin 和 user
//从后台获取的用户角色
const role = "user";
//当进入一个页面是会触发导航守卫 router.beforeEach 事件
router.beforeEach((to, from, next) => {
if (to.meta.roles.includes(role)) {
next(); //放行
} else {
alert(404)
}
});
方式二:
写好路由表和vuex,给所有路由设置一个全局守卫,在进入路由之前进行权限检查,并导航到对应的路由。
二、动态加载菜单和路由(addRoutes)
参考链接:https://www.jb51.net/article/167822.htm