寸不己,一周写一篇已|

雨宮莲

园龄:1年10个月粉丝:3关注:1

若依Vue2.0框架学习之按钮权限(hasPersi)

1. v-hasPermi 在组件内的使用

<el-col :span="1.5">
      <el-button
      type="primary"
      plain
      icon="el-icon-plus"
      size="mini"
      @click="handleAdd"
      v-hasPermi="['system:user:add']"
      >新增</el-button
   >
   </el-col>

2. hasPermi.js

src/directive/permission/hasPermi.js

import store from '@/store'
// 暴露指令对象
export default {
// ==== 指令对象的钩子函数,省略 ====
// inserted ,被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
// ==== 指令对象的钩子函数参数,省略 ====
// el :指令所绑定的元素,可以用来直接操作 DOM
// binding 一个对象,包括:
// name: 指令名,不包括 v- 前缀
// value: 指令的绑定值,这里是['system:user:add']
// oldValue: 指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中使用(无论值是否改变都可用)
  inserted(el, binding, vnode) {
    const { value } = binding
    const all_permission = "*:*:*"; // 特殊权限标识
    // store
    // && 两边是Boolean时,两个都为 true 运算结果为 true
    // && 求值时,如果它们都是真值,则返回最后一个操作数的值,如果有假值,返回第一个假值
    const permissions = store.getters && store.getters.permissions
    // 权限标识存在且为不为空的数组
    if (value && value instanceof Array && value.length > 0) {
      const permissionFlag = value // ['system:user:add']
      // 遍历 store.getters.permissions ,
      // 是否存在: 当前角色有特殊权限 或 自定义指令绑定值数组中元素存在当前登录角色所拥有的某个权限标识
      const hasPermissions = permissions.some(permission => {
        return all_permission === permission || permissionFlag.includes(permission)
      })
// 如果匹配不上,需要把该节点(button)从父节点删除
      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`请设置操作权限标签值`)
    }
  }
}

src/directive/index.js

import hasPermi from './permission/hasPermi'
// installFn 因此需要Vue.use()
const install = function(Vue) {
// 注册一个全局自定义指令 指令名,指令对象
  Vue.directive('hasPermi', hasPermi)
}
// ?
if (window.Vue) {
  window['hasPermi'] = hasPermi
  Vue.use(install);
}
export default install

3. 在main.js 全局注册

import directive from './directive' // directive
Vue.use(directive)

本文作者:雨宮莲

本文链接:https://www.cnblogs.com/pupyy/p/17657254.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   雨宮莲  阅读(1313)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起