自定义指令按钮权限

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>
相关推荐
西岸行者1 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky1 天前
Django入门笔记
笔记·django
勇气要爆发1 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意1 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发2 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
qianshanxue112 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路2 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
土拨鼠烧电路2 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构
烟花落o2 天前
栈和队列的知识点及代码
开发语言·数据结构·笔记·栈和队列·编程学习