前端权限设计实现 (按钮等)

1.使用v-if

//store.state.authIds 为该用户所有的权限 格式为数组 ['home','admin']
<div v-if='authRequest("***")'> </div>
authRequest(auth) {     
      if (auth && !store.state.authIds.includes(auth)) {
        return false;
      } else {
        return true;
      }
    },

2.使用指令

 Vue.directive("auth", {
    inserted: function (el, binding) {     
      if (binding.value && !store.state.authIds.includes(binding.value)) {
        el.parentNode.removeChild(el)
      }
    }
  });
<div v-auth="'***'"> </div>
//指令方式实现的权限控制,使用起来会比较简洁,但是是通过删减 dom 节点的方式实现的,因此只有在第一次时控制。
//指令 也可以在update 时候 去做处理

3.组件

<script>
const authRequest=(auth)=> {     
      if (auth && !store.state.authIds.includes(auth)) {
        return false;
      } else {
        return true;
      }
    },

export default {
    name: 'Authorized',
    functional:true,
    props: {
        authority:{
            type:Array,
            required:true
        }
    },  
    render(h, context) {
        const { props, scopedSlots } = context;
        return authRequest(props.authority) ? scopedSlots.default() : null
    },
}
</script>
<template>
    <Authorized :authority="['admin']" >
        <other-components></other-components>
    </Authorized>
</template>
原文地址:https://www.cnblogs.com/7c89/p/15761719.html