Vue3中,自定义【按钮级权限控制】插件


官方文档:插件 | Vue.js (vuejs.org)

Vue3插件生命周期:

app.directive('custom-directive', {
 // Directive has a set of lifecycle hooks:
  // called before bound element's parent component is mounted
  beforeMount() {},
  // called when bound element's parent component is mounted
  mounted() {},
  // called before the containing component's VNode is updated
  beforeUpdate() {},
  // called after the containing component's VNode and the VNodes of its children 
  // have updated
  updated() {},
  // called before the bound element's parent component is unmounted
  beforeUnmount() {},
  // called when the bound element's parent component is unmounted
  unmounted() {}
})
// (el, binding, vnode)

 

自定义插件:

新建js文件 permission.js ,内容:

import store from '@/store'

export const hasRole = {
    install:(app)=>{
        app.directive('hasRole', {
            mounted(el, binding){

          // roles的值,应为string数组,存放角色列表  例子:['user','proxy']
                // 也可以根据自己的逻辑修改
                const roles = store.getters['acl/role']

              // 使用插件时,绑定的值
                const value = binding.value
          
                let flag =(value.filter(v=>roles.includes(v))).length > 0;
                if (!flag) {
                    if (!el.parentNode) {
                        el.style.display = 'none'
                    } else {
                        el.parentNode.removeChild(el)
                    }
                }

            }
        })
    }
} 

 

修改main.js

import {hasRole} from '@/utils/permission'

const app = createApp(App);

app.use(hasRole)

 

使用:

<button v-hasRole="['admin']">Test</button>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM