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