Vue 自定义指令——鉴权

31 阅读1分钟

需求

根据后台传递的权限参数,加载对应的页面内容

演示代码

<template>

    <button v-has-show="'shop:create'"> 创建 </button>
    <br>
    <button  v-has-show="'shop:edit'"> 编辑 </button>
    <br>
    <button  v-has-show="'shop:delete'"> 删除</button>

</template>

<script setup lang='ts'>
import { Directive } from 'vue';

localStorage.setItem("userId",'xyy')

// 模拟后台数据 => 用户id:模块:权限
const permission = [
    'xyy:shop:edit',
    'xyy:shop:create',
    'xyy:shop:delete',
]

const userId = localStorage.getItem('userId') as string

const vHasShow:Directive<HTMLElement,string> = (el,binding) =>{
    console.log(el,binding)
    if(!permission.includes(userId + ':' + binding.value)){
        el.style.display = 'none'
    }
}

</script>

页面效果

20231125_235620.gif