Vue3自定义全局指令

2023-05-27 14:42:19 浏览数 (3)

自定义的指令功能:根据传参判断是否显隐功能按钮

utils/directives/auth.js 判断方法自己去实现,这里就不贴代码了

代码语言:javascript复制
import useStore from "@/store"

export default (app) => {
    app.directive('auth', {
        mounted(el, binding) {
            hasAuth(el, binding)
        }
    })
}

const hasAuth = (el, binding) => {
    const { user } = useStore()
    const { value } = binding
    if (!value) return
    if (!user.hasPermission(value)) {
        el.parentNode?.removeChild(el)
    }
}

把指令统一导出 utils/directives/index.js

代码语言:javascript复制
import auth from './auth'

export default (app) => {
    auth(app)
}

main.js

代码语言:javascript复制
const app = createApp(App)
import directive from "@/utils/directives"
directive(app)

使用

代码语言:javascript复制
<el-button v-auth="'user_xxxx'">功能按钮</el-button>

0 人点赞