vue自定义按钮级别权限使用实例(自用)
登录的时候先获取按钮权限内容
//获取按钮权限内容
const button = await getUserResources(btntype)
button.data.forEach((element) => {
buttonAll.push(element.name)
})
// 保存至sessionStorage
sessionStorage.setItem('btnContext', JSON.stringify(buttonAll))
utils/btnControl.js
import Vue from 'vue'
export default function btnControl() {
Vue.directive('has', {
inserted: function (el, binding) {
// 获取按钮权限
if (!Vue.prototype.$_has(binding.value)) {
//移除不匹配的按钮
el.parentNode.removeChild(el)
}
},
})
Vue.prototype.$_has = function (value) {
console.log('value: ', value)
let isExist = false
// 从浏览器缓存中获取权限数组
var buttonpermsStr = sessionStorage.getItem('btnContext')
console.log('buttonpermsStr: ', buttonpermsStr)
if (buttonpermsStr === undefined || buttonpermsStr == null) {
return false
} else {
JSON.parse(buttonpermsStr).forEach((element) => {
console.log('element: ', element)
//匹配缓存中的数据中有没有匹配的值
if (element == value) {
// 若在按钮中定义的权限字段能在后端返回的权限数组中能找到,则该按钮可显示
isExist = true
}
})
}
return isExist
}
}
main.js
import btnControl from '@/utils/btnControl'
Vue.use(btnControl)
页面使用 v-has="‘获取的按钮权限字符’"
<template #footer>
<el-button @click="close">取 消</el-button>
<el-button v-has="'保存'" type="primary" @click="save">确 定</el-button>
</template>