1. 程式人生 > 其它 >Vue3中,自定義【按鈕級許可權控制】外掛

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>