vue3封装全局指令

// .directive.ts
const permissionFn = (value: string | string[]) => {
  // 后端返回的是权限数组,存在本地,取出来处理
  const rolesArr = JSON.parse(getItem('roles'))
  if (typeof value === 'string') {
    return rolesArr.includes(value)
  } else {
    return rolesArr.some((item) => value.includes(item));
  }
}
export default {
  mounted(el: Element, binding: any) {
    const permission = binding.value
    if (permission) {
      const hasPermission = permissionFn(permission)
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
}
// main.ts
import App from './App.vue'
import has from './utils/directive'
const app = createApp(App)
app.directive('has', has)
posted @ 2022-05-26 19:45  Life_countdown  阅读(646)  评论(0)    收藏  举报