vue3文档中很简单的描述了一下自定义指令:
<script setup>
const vMyDirective = {
beforeMount: (el) => {
// 在元素上做些操作
}
}
</script>
<template>
<h1 v-my-directive>This is a Heading</h1>
</template>
但是项目中我们一般是批量注册,不用在组件中再单独去引用,下面为批量注册的方式:
第一步、新建directives文件
用来存放不同的指令,我以一个的bounce指令为例:
指令内容:
export default{
name:'debounce',
mounted(el:HTMLElement,binding:any){
console.log(el,binding);
//针对有disable状态的button按钮设置点击后一定时间内禁用
el.addEventListener('click',()=>{
if(!el.disabled){
el.disabled = true;
// 若没绑定时间间隔,默认3秒后可再次点击
setTimeout(()=>{
el.disabled = false;
},binding.value || 3000);
}
});
}
};
第二步、批量导入注册指令
可以在合适的位置新建一个文件用于导入directives中创建的所有指令,我在另一个文件夹中建立一个叫directive的文件,
批量导入注册内容:
//批量导入注册指令
//此方法为vite提供的导入文件方法
const directives = import.meta.globEager('/src/directives/*.ts');
export default {
install:(app:any,options:{[key:string]:any})=>{
for(const directive of Object.values(directives)){
const {name} = directive.default;
if(name) app.directive(name,directive.default);
}
}
};
第三步、main.ts中引入批量指令插件
...
import directivePlugin from '@/boot/directive';
...
app.use(directivePlugin);
第四步、直接使用
在任意标签中使用自定义指令 v-debounce
<button v-debounce="'123'">保存</button>
就可以啦!
例如这个就可以对应第一步的指令内容,控制台会打印出el和123