Vue自定义指令完成按钮级别的权限判断

权限指令,对按钮权限的控制

1.登录成功后,获取后台返回所有的按钮权限,存到sessionStorage中( 也可以存到vuex )

2.在main.js中自定义指令

3.定义指令,如果用户含有此按钮权限,则在页面显示出来( v-has绑定进行逻辑判断 )


登录成功后,获取后台返回所有的按钮权限,存到sessionStorage中

// 4.5获取当前登录用户角色权限列表   这个方法在登录中调用
roleUserInfo() {
  this.$ajax.get("/role/permissionlist").then(res => {
      sessionStorage.setItem("loginVal", JSON.stringify(res.data.data));
        setTimeout(() => {
          window.location.reload();
        }, 50);
      });
}

在main.js中自定义指令

//inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)
//如果bind获取不到el.parentNode
//试试把 bind 改为 inserted
const has = Vue.directive("has", {
    inserted: function(el, binding) {
        console.log(binding,"w")
        // 获取按钮权限// 获取按钮权限
        if (!Vue.prototype.$_has(binding.value)) {
            el.parentNode.removeChild(el);
        }
    }
});
//// 权限检查方法(且把该方法添加到vue原型中)
Vue.prototype.$_has = function(value) {
    console.log(value,"f")
    let isExit = false;
    let buttonpermsStr = JSON.parse(sessionStorage.getItem("loginVal"));
    
    if (buttonpermsStr === undefined || buttonpermsStr=== null) {
        return false;
    }
    for (let i = 0; i < buttonpermsStr.length; i++) {
        let buttonpermsStrId = buttonpermsStr[i]
        console.log(buttonpermsStrId.id,'wer')
        if (buttonpermsStrId.id == value) {
            isExit = true;
            break;
        }
    }
    return isExit;
};
export { has };

定义指令,如果用户含有此按钮权限,则在页面显示出来( v-has绑定进行逻辑判断 )

<!-- 在按钮上直接写上v-has="后台返回的按钮id" -->
<Button v-has="'97'">查看</Button>

猜你喜欢

转载自www.cnblogs.com/home-/p/11888720.html
今日推荐