vue @click 多次触发解决

场景:

提示:同事写了个普通的点击事件:

例如:@click="xxx" xxx是点击事件要执行的 结果每次点击就会触发两次

解决方案1:

提示:e.preventDefault:

例如:

@click="xxx($event)"

xxx(e){

e.preventDefault();

}

当然 如果你是一次性的不需要多去触发去更新状态 可以用vue的 v-on:click.once="xxx" xxx就是对应的点击方法

解决方案2:disabled

提示:设置不可见执行成功之后再放开:

 html:

<el-button type="primary" :disabled="disabled"  :size="GLOBAL.topButtonSize" @click="saveArea"
          ><i class="iconfont icon_save"></i><font>保存</font>
          </el-button>

 js:

//保存信息
		saveArea(){
			this.isLoading=true;
			this.disabled =true
			  saveUserAareWithFlag({"userAreaList":userAreaList,userId:this.userInfo.userId,flag:this.flag}).then((res)=>{
			    if (res.data.code == 0) {
			      this.$notify({
			        title: '成功',
			        message: '保存成功',
			        type: 'success'
			      });
				  this.isLoading=false;
				  this.disabled =false
			      this.$emit('setNodeClick');
			      this.$emit('closeEditBox');
			    } else {
					this.isLoading=false;
					this.disabled =false
			      this.$notify({
			        title: '失败',
			        message: res.data.message,
			        type: 'error'
			      })
			    }
			  })
		},
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 || 1000)
          }
        })
      }
    })
  }
}
// 防抖
export const Debounce = (fn, t) => {
  let delay = t || 500;
  let timer;
  console.log(fn)
  console.log(typeof fn)
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  }
};


// 节流
export const Throttle = (fn, t) => {
  let last;
  let timer;
  let interval = t || 500;
  return function () {
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        last = now;
        fn.apply(this, args);
      }, interval);
    } else {
      last = now;
      fn.apply(this, args);
    }
  }
};

当然 如果你是一次性的不需要多去触发去更新状态 可以用vue的 v-on:click.once="xxx" xxx就是对应的点击方法。另外也可以在点击时起一个变量 用来锁定 当你需要再次操作时在放开例如方案2里js部分。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值