vue3中,在h()函数内使用自定义指令
首先将自定义指令汇总
/*
为了方便管理自定义指令
在src下新建directive专门放自定义指令
文件夹directive下新建auth.js(指令之一)和index.js
*/
// auth.js:
const auth = {
mounted(el, binding) {
// 获取页面按钮是否展示
if (binding.value) {
// isTrue为判断是否展示
if (!isTrue) {
if (el.parentNode) {
el.parentNode.removeChild(el);
}
}
}
},
};
export default auth;
// index.js
import auth from './auth'
export default {
auth
}
然后为了统一注册所有的指令,在main.js中
// 引入所有指令
// 自定义指令
import dire from '@/directive/index'
import { createApp } from 'vue'
//注册所有指令
const app = createApp(App)
for (let key in dire) {
app.directive(key, dire[key]); // key要和指令名称一样
}
接下来进入正题:在h()函数中使用自定义指令
// 首先引入resolveDirective, withDirectives这两个方法
import { ref, resolveDirective, withDirectives } from 'vue'
// 将自定义的指令引入
const authDir = resolveDirective('auth')
/*
这里是原来h()函数的使用
h(NButton, {
size: 'small',
type: "info",
}, { default: () => '编辑' })
*/
/*
加入自定义指令后:
*/
withDirectives(h(NButton, {
size: 'small',
type: "info",
}, { default: () => '编辑' }), [[authDir, 'xxxxx']])
// authDir是上方引入的自定义指令,xxxx是指令的值
ok了