vue权限管理系统的实现代码

2020-06-13 10:42:52易采站长站整理

meta: routerList[j].meta,
children: [] };

if (routerList[j].children.length) {
for (let k = 0; k < routerList[j].children.length; k++) {
let _fullpath = routerList[j].children[k].path
if (routerList[j].children[k].meta) {
_fullpath = routerList[j].children[k].meta.parentPath + '/' + _fullpath
}
if (menuMap['AuthRule::' + _fullpath]) { // 找到二级菜单
obj.children.push(routerList[j].children[k]);
}
}
}
}
if (obj) {
routerArr.push(obj);
this.$router.options.routes.push(obj);
}
}

storage.set("routerArr", routerArr);
this.$router.addRoutes(routerArr);
this.$router.push({ path: "/" });
},

menuMap为登录时获取的权限菜单,是一个对象; routerList为前端定义的路由表;遍历routerList,如果routerList的key在menuMap里能找到的话,就表示该路由存在。最后生成一个过滤后的路由表,用vue提供的addRoutes方法动态添加到路由中,并把过滤后的路由表存到本地。


const menuMap = {
'/dashboard': {path: '/dashboard', name: '首页'}
}
const routerList = [
{path: '/dashboard', name: '首页', component: ..}
]

在页面刷新的时候,从本地获取路由表,添加到路由表中,代码如下,constRouterArr为基础路由表,比如登录,404等


const routerList = storage.get('routerArr')
const routerArr = constRouterArr.concat(routerList);

对于按钮的权限


if (res.data.auth_rule_map) {
let obj = {}
Object.keys(res.data.auth_rule_map).forEach(i => {
// 将所有的按钮放到一个obj里 key 为接口地址
if (res.data.auth_rule_map[i].is_menu === 0) { // 如果是按钮
obj[res.data.auth_rule_map[i].rule] = 1
}
})
storage.set("btnList", obj);
storage.set("menuTree", res.data.auth_rule_map);
}

auth_rule_map为接口返回权限map,把按钮的权限过滤出来存到本地。

将map添加到每个路由组件的data里,(这里有一个问题,怎么判断一个组件是否是路由组件),目前想到的是通过组件name来判断,把所有的路由组件放到一个数组里做判断。

在组件内部的按钮上加上v-if,如果this.uri__里的uri在uriMap里存在就显示。

也可以通过方法来判断,如下面的__isBtnShow,不仅可以控制按钮的显示隐藏,还可以控制其样式,比如颜色等,更加灵活,推荐使用方法来控制


uri = {
ADD_MEMBER: '/api/add_member'
}

export default function install (Vue) {
const uriMap = storage.get('btnList')