自定义指令按钮权限

1、指令文件

javascript 复制代码
// 判断按钮权限逻辑
const checkPermission = (el, binding) => {
  // 获取自定义指令传过来的数组(binding.value)
  const btnRoles = binding.value
  console.log(btnRoles)
  // 取一下本地存的账号权限
  // const userRoles = JSON.parse(localStorage.getItem('role'))
  const userRoles = ['super', 'normal']
  // 判断自定义指令的传值,在账号权限数组中能否找到
  if (btnRoles) {
    // 能找到返回true
    const hasPermission = userRoles.some((v) => {
      return btnRoles.includes(v)
    })
    // 找不到返回false,使用自定义指令的钩子函数,操作dom元素删除该节点
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`传入关于权限的数组,如 v-permission="['super','normal']"`)
  }
}

// 导出一个对象用作自定义指令的第二个参数
export default checkPermission

2、main.js文件引入,挂载在vue实例上

javascript 复制代码
import checkPermission from './plugins/directive/permission'
const app = createApp({})
app.directive('permission', checkPermission)
app.mount('#app')

3、页面使用

html 复制代码
    <Button v-permission="'super'">super</Button>
    <Button v-permission="'normal'">normal</Button>
    <Button v-permission="'other'">other</Button>
相关推荐
雷工笔记20 小时前
MES学习笔记之SCADA采集的数据如何与MES中的任务关联起来?
笔记·学习
繁星星繁20 小时前
【C++】脚手架学习笔记 gflags与 gtest
c++·笔记·学习
2301_8107463121 小时前
CKA冲刺40天笔记 - day20-day21 SSL/TLS详解
运维·笔记·网络协议·kubernetes·ssl
YJlio1 天前
SDelete 学习笔记(9.18):安全删除、空闲清理与介质回收实战
笔记·学习·安全
7441 天前
数据结构(C语言版)线性表-单链表的拓展及应用
笔记·强化学习
xiaozi41201 天前
Ruey S. Tsay《时间序列分析》Python实现笔记:综合与应用
开发语言·笔记·python·机器学习
d111111111d1 天前
STM32低功耗学习-停止模式-(学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习
@游子1 天前
Python学习笔记-Day5
笔记·python·学习
摇滚侠1 天前
2025最新 SpringCloud 教程,网关功能、创建网关,笔记51、笔记52
java·笔记·spring cloud
浓墨染彩霞1 天前
Java-----多线路
java·经验分享·笔记