美文网首页VUE
vue防重复点击(指令实现)

vue防重复点击(指令实现)

作者: cain07 | 来源:发表于2021-08-03 08:32 被阅读0次

1.快速点击按钮会重复多次调用接口,防止出现这样的情况

  • 全局定义,方便调用
export default {
  install (Vue) {
    // 防重复点击(指令实现)
    Vue.directive('preventReClick', {
      inserted (el, binding) {
        el.addEventListener('click', () => {
          if (!el.disabled) {
            el.disabled = true
            setTimeout(() => {
              el.disabled = false
            }, binding.value || 3000)
          }
        })
      }
    })
  }
}
import Vue from 'vue'

const preventReClick = Vue.directive('preventReClick', {
    inserted: function (el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 3000)
            }
        })
    }
});

export { preventReClick }
  • 在main.js中引用
import preventReClick from './store/preventReClick' //防多次点击,重复提交

  • 按钮调用直接加v-preventReClick
<el-button type="prismary" style="width:100%;" @click="handleSubmit" v-preventReClick></el-button>

2.利用延时处理


<script>
    var isClick = true;
    $("button").on("click",function(){
        if(isClick) {
            isClick = false;
            //事件
            console.log($(this).attr("data-val"));
            //定时器
            setTimeout(function() {
                isClick = true;
            }, 1000);//一秒内不能重复点击
        }
    });
</script>

相关文章

网友评论

    本文标题:vue防重复点击(指令实现)

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