vue通自定义指令实现按钮权限控制

VUE自定义指令

在没有使用

将一个自定义指令全局注册到应用层级

const app = createApp({})

// 使 v-focus 在所有组件中都可用
app.directive('focus', {
  /* ... */
})

权限控制简单例子

main.ts文件

import { registerGlobalDirective } from './directive'
const bootstrap = async ()=>{
	const app = createApp(App)
	registerGlobalDirective(app)
	app.mount('#app')
}

directive/src/auth.ts

/**
 * 将一个自定义指令全局注册到应用层级
 * @Example v-auth=""
 */
import type { Directive, DirectiveBinding } from 'vue'
export interface ContextOptions {
  hasPermission: (
    value?: string | string[] | undefined,
    def?: boolean,
  ) => boolean
}
let context: ContextOptions = {
  hasPermission: () => false,
}
const isAuth = (el: Element, binding: any) => {
  const { value } = binding
    const all_permission = "*:*:*";
    const permissions = ['1','2','3','4','5']//权限数组
    if (value) {
      const permissionFlag = value
      const hasPermissions = permissions.some(permission => {
        return all_permission === permission || permission == permissionFlag
      })
      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`请设置操作权限标签值`)
    }
}

const mounted = (el: Element, binding: DirectiveBinding) => {
  isAuth(el, binding)
}

const auth: Directive = {
  mounted,
}

export { auth }

directive/index.ts

import type { App } from 'vue'
import { auth } from './src/auth'
export { auth}

export const registerGlobalDirective = (app: App) => {
  app.directive('auth', auth)
}

index.vue文件



更多自定义指令例子

分享8个非常实用的Vue自定义指令 (baidu.com)

你可能感兴趣的:(vue.js,javascript,前端)