- 在directive文件下新建 debounce.js
// 函数防抖 指令(v-debounce), 限制0.3s内点击多次只执行最后一次
export default {
inserted: function (el, binding) {
let timer
el.addEventListener('click', () => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
binding.value()
}, 300)
})
}
}
- 在main.js引入并注册事件
// 自定义指令
import directive from './directive'
for (const n in directive) {
Vue.directive(n, directive[n])
}
- 在组件中使用
<!-- handleConfirm 要执行的点击事件 -->
<el-button
type="primary"
v-debounce="handleConfirm">保存</el-button>