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>