main.js
// 防止重复点击生成重复数据
const throttle = {
bind: (el, binding) => {
let throttleTime = binding.value // 防抖时间
if (!throttleTime) {
throttleTime = 1000 // 不设置防抖时间,则默认1s
}
let timer
let disable = false
el.addEventListener(
"click",
(event) => {
if (timer) {
clearTimeout(timer)
}
if (!disable) {
// 第一次执行(一点击触发当前事件)
disable = true
} else {
event && event.stopImmediatePropagation()
}
timer = setTimeout(() => {
timer = null
disable = false
}, throttleTime)
},
true
)
},
}
Vue.directive("throttle", throttle)
使用
<el-button v-throttle="5000" @click="handleSubmit()">提交</el-button>
该文章介绍了如何在Vue.js中创建一个自定义指令`v-throttle`,用于防止用户快速连续点击按钮时生成重复数据。通过设置防抖时间,可以限制事件处理函数的执行频率,例如在5秒内只允许最后一次点击生效。
1163





