VUE按钮权限全局指令

在main.js注册

import has from './has';
 
页面调用
 
v-has='某某'
 
has.js内容
import Vue from 'vue'

/**权限指令**/
const has = Vue.directive('has', {
    bind: function (el, binding, vnode) {
        // 获取页面按钮权限
        let btnPermissions = [];
        if (binding.value) {
            // 如果指令传值,获取指令参数,根据指令参数和当前登录人按钮权限做比较。
            btnPermissions = binding.value;
            console.log(btnPermissions, '这里是指令绑定的参数')
        } else {
            // 用不到------------------
            btnPermissions = vnode.context.$route.meta.btnPermissions; //用不到-------------------
        }
        if (!Vue.prototype.$_has(btnPermissions)) { //调用判断函数
            el.style.display = 'none'; //隐藏按钮
        }
    }
});
//截取下标
function find(str, cha, num) {
    var x = str.indexOf(cha);
    for (var i = 0; i < num; i++) {
        x = str.indexOf(cha, x + 1);
    }
    return x;
}
const btnArr = JSON.parse(localStorage.getItem("cparkbtnList")) //此数组就是从后端获取的数组
console.log(btnArr,'后端获取的数组')
// 权限检查方法
Vue.prototype.$_has = function (value) {
    const path = location.pathname + location.search //获取路由
    const pathTrue = path.split('?')[0] //去除参数
    const index = find(pathTrue, '/', 1) //获取第二份'/'下标
    const keypath = pathTrue.substring(index) //取得正确的key值
    let isExist = false;
    // 获取用户按钮权限
    let btnPermissionsArr = [] //获取当前页面的权限
    btnArr.forEach(item => {
        if (item.menuUrl == keypath) {
            btnPermissionsArr = item.buttonList
        }
    });
    //判断是否存在
    if (btnPermissionsArr == undefined || btnPermissionsArr == null) {
        return false;
    }
    if (btnPermissionsArr.indexOf(value) > -1) {
        isExist = true;
    }
    console.log(isExist)
    return isExist;
};
export {
    has
}

 

 
posted @ 2021-06-10 10:36  嘿,你好!  阅读(589)  评论(0编辑  收藏  举报