全局指令
先写一个js文件
import store from '@/store'
const directivePlugin = {install(Vue) {Vue.directive('checkBtn', {inserted(el, binding) {// el: 指令绑定的那个元素对象 dom// binding.value: 指令等于号后面绑定的表达式的值 v-if="xxx"// 拿到el 拿到value 配合权限数据 做按钮显示隐藏控制// 控制逻辑: 判断当前的按钮自身的权限标识能否在后端返回的points中找到 如果找到 证明要显示// 如果找不到 证明要隐藏// 1. 权限数据 -> points // 2. binding.value -> 按钮自身的标识const points = store.state.user.userInfo.roles.pointsif (!points.includes(binding.value)) {// 把当前的按钮移除// 移除eldom 1. remove() 2. 先找到父节点 removeChildel.remove()}}})}
}export default directivePlugin
在main.ts文件中注册
在文件中使用
局部注册
先建立一个js文件
import store from "@/store";function checkPermission(el, binding) {const { value } = binding; //['admin']const roles = store.getters && store.getters.roles;console.log(roles, "roles");const permissions = store.getters && store.getters.permission; //空数组console.log(permissions, "permissions");if (value && value instanceof Array) {if (value.length > 0) {const permissionRoles = value;console.log(permissionRoles, "values"); //['admin']const hasRole = roles.some((role) => {return permissionRoles.includes("ROLE_" + role.roleCode);});// console.log(hasRole, "hasRole");//trueconst hasPermission = permissions.some((permissions) => {return permissionRoles.includes(permissions);});console.log(hasPermission, "hasPermission");if (!hasPermission && !hasRole) {console.log(111);el.parentNode && el.parentNode.removeChild(el);}}} else {throw new Error(`need roles! Like v-permission="['admin','editor']"`);}
}export default {inserted(el, binding) {console.log(el, binding);checkPermission(el, binding);},update(el, binding) {checkPermission(el, binding);},
};
在文件中使用
<div class="filter-container" v-permission="['SUPERADMIN']"><el-button type="primary" @click="addUser"><i class="el-icon-plus"></i>添加用户</el-button></div>
在文件中定义
import permission from "@/directive/permission/permission.js";
export default {directives: {permission,},
}