Vue~添加按钮权限~通过自定义指令

1、需求

客户:需要把导入、删除权限化;指定人员有权限;

2、思路

后台有一个接口,是可以查询到当前登录人的权限;

前端方案:

1、每到一个页面就请求一次接口是否有权限;(太麻烦了)

2、自定义指令 · Vue.directive;(一次请求,一直用)

3、代码实现

1、自定义指令

创建 /directive/permission/hasPermi 文件

//用来获取权限数据
import store from '@/store'

export default {

  inserted(el, binding, vnode) {
    //获取绑定值
    const { value } = binding
    // TODO 匹配规则,在页面写的要对应这个匹配规则
    const all_permission = "*:*:*";
    //获取用户权限数据
    const permissions = store.getters && store.getters.permissions 
if (value && value instanceof Array && value.length > 0) { 
      //权限标志
      const permissionFlag = value
      //判断用户是否有此权限
      const hasPermissions = permissions.some(permission => {
        console.log('permission', permission);
  return all_permission === permission || permissionFlag.includes(permission)
      })
      
      //没有权限-移除页面上的控件
      if (!hasPermissions) {{
        console.log('没有权限-移除');
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else { 
      el.parentNode && el.parentNode.removeChild(el)
      throw new Error(`请设置数组操作权限`)
    }
  }
}
 

2、注册指令

创建 /directive/permission/index文件


import hasPermi from './hasPermi'
import Vue from "vue"


const install = function (Vue) {
  Vue.directive('hasPermi', hasPermi)
}


if (window.Vue) {
  window['hasPermi'] = hasPermi
  Vue.use(install);
}

export default install

3、在main.js里面进行全局注册


import permission from './directive/permission'


Vue.use(permission)

vue官网对指令的解释https://cn.vuejs.org/v2/guide/custom-directive.html

4、使用方法

      <button
           v-has-permi="['btn:pre:del']"
           style="margin-top: 4px"/>


   <button
           v-has-permi="['btn:pre:export']"
           style="margin-top: 4px"/>

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夢鑰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值