美文网首页
vue2实现点击按钮防抖自定义事件

vue2实现点击按钮防抖自定义事件

作者: 瓩千瓦 | 来源:发表于2023-04-20 11:39 被阅读0次
  1. 在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)
        })
    }
}
  1. 在main.js引入并注册事件
// 自定义指令
import directive from './directive'

for (const n in directive) {
    Vue.directive(n, directive[n])
}
  1. 在组件中使用
<!-- handleConfirm 要执行的点击事件 -->
<el-button 
    type="primary"
    v-debounce="handleConfirm">保存</el-button>

相关文章

网友评论

      本文标题:vue2实现点击按钮防抖自定义事件

      本文链接:https://www.haomeiwen.com/subject/lylbddtx.html