1.在入口文件App.vue中定义
<template>
<div id="app">
<routerView/>
</div>
</template>
<script>
import Vue from 'vue'
Vue.directive('has',{
bind(el, binding, vnode) {
if (!Vue.prototype.$_has(binding.value)) {
vnode.context.$nextTick(() => el.parentNode.removeChild(el));
}
}
})
// 权限检查方法
Vue.prototype.$_has = function(value) {
if (!value) throw new Error('v-has方法参数不能为空');
let authStr = window.localStorage.getItem('auth');
if (authStr === undefined || authStr === null) {
return false;
}
let authTable = authStr.split(',');
if(authTable.some(v => v == value)){
return true;
}else{
return false;
}
};
export default {
created() {
this.setAuthInfo();
},
name: "App",
computed: mapState(["Num"]),
methods: {
setAuthInfo(){
let authTable = [
{
"id": 275, // 菜单ID
"moduleId": null,
"moduleCode": "",
"moduleName": "WIP管理", // 菜单名称
"viewList": [
{
"id": 278,
"moduleId": null,
"moduleCode": "",
"moduleName": "WIP盘点履历",
"viewList": [
{
"id": 279,
"moduleId": null,
"moduleCode": "",
"moduleName": "新建",
"viewList": null,
},
{
"id": 280,
"moduleId": null,
"moduleCode": "",
"moduleName": "提交",
"viewList": null,
}
],
}
],
},
]
//获取table中的id字段,放在数组ids中
let ids = [];
this.getAuthIds(authTable,ids);
//把ids数组放在localStorage中
window.localStorage.setItem('auth',ids);
},
getAuthIds(table,ids){
for(let i = 0 ; i<table.length ; i++){
ids.push(table[i].id);
if(table[i].viewList != null && table[i].viewList.length >0){
this.getAuthIds(table[i].viewList,ids);
}
}
}
}
};
</script>
<style>
html,
body,
#app {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
指令使用:
通过v-has指令控制按钮显隐。如果v-has指令返回true,则按钮显示,返回false,按钮不显示。
<el-button @click=" dialogVisibleAdd = true" v-has="'279'">新建</el-button>
也可以用这种方式:
<el-button @click=" dialogVisibleAdd = true" v-if="flag ">新建</el-button>
let flag = this.$_has('279');
实现原理后续再补充吧~