vue3 自定义指令防抖和节流代码
时间: 2023-10-20 12:06:28 浏览: 102
vue中使用防抖和节流
可以参考以下代码实现:
// 防抖指令
Vue.directive('debounce', {
inserted: function (el, binding) {
let timer
el.addEventListener('input', () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
binding.value()
}, binding.arg || 1000)
})
}
})
// 节流指令
Vue.directive('throttle', {
inserted: function (el, binding) {
let lock = false
el.addEventListener('click', () => {
if (lock) return
lock = true
setTimeout(() => {
binding.value()
lock = false
}, binding.arg || 1000)
})
}
})
阅读全文