1, vue2 项目移植自定义指令到vue3 失效
在升级vue3项目(vue-element-admin: https://panjiachen.github.io/vue-element-admin-site/)时, 发现vue2的指令功能失效, 查阅资料发现这是一个break升级.
所以需要修改directive使用方法和结构
2, 重写directive
src/directive/permission/test.js
import store from '@/store'
export const Permission = app => {
app.directive('permission', {
mounted(el, binding) {
const RoleID = store.getters.currentRoleID
// el: 当前标签 binging.value: v-permission绑定的值
// console.log('el',el);
// console.log('binding.value', binding.value)
if (binding.value && RoleID !== binding.value) {
if (binding.value.length > 0) {
const permissionRoles = binding.value
if (!permissionRoles.includes(RoleID)) {
console.log("delete");
console.log(el.parentNode);
el.parentNode.removeChild(el)
}
}
} else {
throw new Error(`need roles! Like v-permission="['admin','editor']"`)
}
}
})
}
// vue 中指令的钩子:
一个指令定义对象可以提供如下几个钩子函数 (均为可选):
created:在绑定元素的 attribute 或事件监听器被应用之前调用。在指令需要附加在普通的 v-on 事件监听器调用前的事件监听器中时,这很有用。
beforeMount:当指令第一次绑定到元素并且在挂载父组件之前调用。
mounted:在绑定元素的父组件被挂载前调用。
beforeUpdate:在更新包含组件的 VNode 之前调用。
updated:在包含组件的 VNode 及其子组件的 VNode 更新后调用。
beforeUnmount:在卸载绑定元素的父组件之前调用
unmounted:当指令与元素解除绑定且父组件已卸载时,只调用一次。
原文: https://v3.cn.vuejs.org/api/application-api.html#directive
src/store/module/user.js
const state = {
roles: ['admin'],
}
src/store/getters.js
const getters = {
roles: state => state.user.roles,
}
export default getters
3, 注册directive到全局
main.js
// 注册自定义指令
import * as Directives from '@/directive/permission/test'
Object.values(Directives).forEach(fn => fn(app))
4, 直接在vue文件中使用, 不需要额外引入
// 若v-test="'admin'", 则存在permissionList, 会显示
// 若v-test="'editor'", 则不存在permissionList, 不会显示
<div v-test="'editor'">hello world</div>