应用场景举例:管理系统中不同角色的用户,拥有不同的操作按钮,如:
- 管理员:创建,编辑,删除
- 普通用户:编辑,删除
- 游客:编辑
这里我们用到了vue3的自定义指令 Directive
<template>
<button v-has-show="'shop:create'">创建</button>
<button v-has-show="'shop:edit'">编辑</button>
<button v-has-show="'shop:delete'">删除</button>
</template>
<script setup lang="ts">
import type { Directive } from "vue";
localStorage.setItem('userId', 'zhou')
//模拟后台穿过来的权限列表
const permission = [
'zhou:shop:create',
'zhou:shop:edit',
'zhou:shop:delete',
]
const userId = localStorage.getItem('userId') as string
const vHasShow: Directive<HTMLElement, string> = (el, bingding) => {
console.log(el, bingding);
if (!permission.includes(userId + ':' + bingding.value)) {
el.style.display = 'none'
}
}
</script>