美文网首页
Vue自定义指令实现按钮级别权限

Vue自定义指令实现按钮级别权限

作者: Taijia | 来源:发表于2020-09-03 17:31 被阅读0次

一、src文件夹下新建utils文件夹,文件夹下新建authoruty.js文件:

/**
 * 检查权限点工具函数
 * @param {*} permissionCode 元素权限点
 * @param {*} permissions 所有权限点
 */
export function checkAuthority(permissionCode, permissions) {
  let hasPermission = true;
  
  if (permissionCode) {
    if (permissionCode instanceof Array && permissionCode.length > 0) {
      hasPermission = permissions.some(it =>
        permissionCode.includes(it)

      );
      console.log('permissionCode---', permissionCode)
      console.log('hasPermission---1', hasPermission)
    } else {
      hasPermission = permissions.some(item => item === permissionCode);
      console.log('hasPermission---2', hasPermission)
    }
  }
  return hasPermission;
}

二、src文件下新建directive文件夹,随之再建立Authority文件夹,并在其下新建Authority.js文件和index.js文件,

  1. Authority.js文件代码:
import store from "@/store";
import { checkAuthority } from "@/utils/authority";
// console.log('store-----', store.state.user.permission)
console.log("store-----", store);
export default {
  inserted(el, binding, vnode) {
    const { value } = binding;
    const permissions = JSON.parse(localStorage.getItem('permissionData')) || []
    console.log('permissionList---', permissions)
    const hasPermission = checkAuthority(value, permissions);
    if (!hasPermission) {
      // eslint-disable-next-line no-unused-expressions
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      } else {
        el.innerHTML = "";
      }
    } else {
      el && el.setAttribute("code", value);
    }
  },
};
  1. index.js文件代码:
import authority from './Authority';
// eslint-disable-next-line func-names
const install = function(Vue) {
  Vue.directive('authority', authority);
};

if (window.Vue) {
  window.authority = authority;
  Vue.use(install); // eslint-disable-line
}

authority.install = install;
export default authority;

(备注: 权限点集合permissionData在登录时已经存到localStorage里面了,取值,直接JSON.parse(localStorage.getItem('permissionData')))
三、main.js文件里引入:

import AuthorityDirective from '@/directive/Authority/index.js';  // 自定义指令
Vue.use(AuthorityDirective);

四、使用:

<el-button type="primary" v-authority="['Table_Write']">show</el-button>

补充:
权限点集合是一个纯数组集合,该数据模拟从后台获取到的数据:

permissionData = ['Table_Write', 'Table_Read', 'Form_Write', 'Form_Read']

获取到后,在登录时立即存入localStorage。

相关文章

网友评论

      本文标题:Vue自定义指令实现按钮级别权限

      本文链接:https://www.haomeiwen.com/subject/eeuvsktx.html