一般来讲,自定义指令当中不需要用到那么多生命周期钩子函数,很多时候我们只关注mounted和updated。这时就可以将自定义指令简写为以下这种形式:
const vHasShow:Directive = (el:HTMLElement,binding:DirectiveBinding) => {}
自定义指令鉴权:
App.vue
<template>
<button v-has-show="'create'">创建</button>
<button v-has-show="'edit'">编辑</button>
<button v-has-show="'delete'">销毁</button>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { Directive, DirectiveBinding } from 'vue'
// Mock数据
let premission = [
'xiaomanzs:shop:edit',
'xiaomanzs:shop:create',
// 'xiaomanzs:shop:delete',
]
// 获取userId,只有当id+:shop:+操作名称完整对应上permission中的元素时才认定为有权限,此时按钮会被展示出来
sessionStorage.setItem('userId', 'xiaomanzs')
const userId = sessionStorage.getItem('userId')
const vHasShow: Directive<HTMLElement, DirectiveBinding> = (el, binding) => {
if (!premission.includes(userId + ':shop:' + binding.value)) {
el.style.display = 'none'
}
}
</script>
<style scoped>
button {
margin: 20px;
}
</style>
其核心思想是用户id+:shop:+模板中为指令设置的实参组成的字符串必须是premission数组中的元素才会展示按钮,否则按钮的display将被设置为none(隐藏)