- 在src目录下新建directives文件夹,然后在文件夹中新建一个permission.ts文件,代码如下
import session from '@/utils/session';
import type { ObjectDirective } from 'vue';
const userInfo = session.get('userInfo');
const getRole = () => {
if (userInfo && userInfo.userAuths && userInfo.userAuths[0] && userInfo.userAuths[0].roleId) {
return userInfo.userAuths[0].roleId;
}
return '';
};
//处理角色权限的代码
const permission: ObjectDirective = {
mounted(el: any, binding: any) {
const { value } = binding;
const role = getRole();
if (value && value instanceof Array && value.length > 0) {
const permissionRoles = value;
const hasPermission = permissionRoles.includes(role);
if (!hasPermission) {
// eslint-disable-next-line no-unused-expressions
el.parentNode && el.parentNode.removeChild(el);
}
} else {
throw new Error('need roles! Like v-permission="["admin","editor"]"');
}
},
};
export default permission;
- 在需要使用该指令的文件夹中引入使用
<template>
<el-button
v-permission="['admin']"
</el-button>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, onUnmounted, Ref, ref, unref } from "vue";
import permission from "@/directives/permission";
export default defineComponent({
name: "Examine",
directives: {
permission
},
components: {
},
setup() {
}
});
</script>
<style scoped lang="scss">
</style>