vue3-自定义指令

创建自定义指令:v-permission

1. src文件夹下创建directives文件夹,方便对自定义指令进行统一管理封装

vue3-自定义指令_第1张图片

// permission.js

import store from '@/store'
function checkPermission (el, binding) {
  const { value } = binding
  const points = store.getters.userInfo.permission.points
  if (value && value instanceof Array) {
    const hasPermission = points.some(point => {
      return value.includes(point)
    })
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error('v-permission value is ["admin",...]')
  }
}

export default {
  mounted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}

index.js 自定义指令统一导出出口 

// index.js

import permission from '@/directives/permission'

export default app => {
  app.directive('permission', permission)
}

 main.js中导入自定义指令

// main.js

import registerDirectives from '@/directives'

const app = createApp(App)
registerDirectives(app)
app.mount('#app')

视图中的使用


            {{ $t('msg.role.assignPermissions') }}

你可能感兴趣的