vue3中,全局自定义指令——DirectiveBinding & v-throttle节流-保存和提交按钮时间间隔内点击多次只执行一次
页面
<el-button
v-throttle="3000"
type="primary"
@click="save"
>
保存
</el-button>
方法
library\plugins\directive.ts
import type { DirectiveBinding } from 'vue'
export function setup(app: any) {
/**
* @description 自定义节流指令v-throttle
*/
app.directive('throttle', {
mounted(el: any, binding: DirectiveBinding) {
let { throttleTime } = binding.value
if (!throttleTime) {
throttleTime = 1000
}
let timer: any
let disable = false
el.addEventListener(
'click',
(event: any) => {
if (timer) {
clearTimeout(timer)
}
if (!disable) {
disable = true
} else {
event && event.stopImmediatePropagation()
}
timer = setTimeout(() => {
timer = null
disable = false
}, throttleTime)
},
true
)
},
})
}
附:自定义vue3指令
在vue3中,自定义指令需要使用directive函数来自定义指令
import {createApp} from 'vue'
const app = createApp({})
app.directive('demo',{
//指令绑定到元素时调用
mounted(el,binding){
console.log(binding.value)
},
//指令与元素解绑时调用
unmounted(el,binding){}
})
定义一个v-demo
的指令,当该指令绑定到元素时,会调用mounted方法,并传入两个参数:元素本身和指令对象(包含了一些属性,比如:值、修饰符等),当指令与元素解绑时,会调用unmounted方法。
使用指令
<div v-demo="hello world">
自定义指令
</div>
这样,在页面渲染完成后,控制台就会输出字符串“hello world”
。
注意:在vue3中,不能通过全局注册方式来注册自定义指令。必须要在应用实例上使用directive()
方法进行注册。