vue实现节流,防止重复提交

1、在methods中定义节流函数:

/**
* @desc 函数节流,规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。
* @param func 函数
* @param wait 延迟执行毫秒数
*/
throttle (func, wait) {
  let timeout = null
  return function () {
      const context = this
      const args = arguments
      if (!timeout) {
          timeout = setTimeout(() => {
              timeout = null
              func.apply(context, args)
          }, wait)
      }
  }
}

2、在data中定义绑定需要节流的函数:

data() {
  this.handleLogin = this.throttle(this.handleLogin, 1000);
  return {}
 },
methods: {
  handleLogin() {
    console.log('handleLogin')
  },
  throttle (func, wait) {
    let timeout = null
    return function () {
      const context = this
      const args = arguments
      if (!timeout) {
          timeout = setTimeout(() => {
              timeout = null
              func.apply(context, args)
           }, wait)
       }
     }
  }
}

转载自:https://www.cnblogs.com/jardeng/p/13750928.html

你可能感兴趣的:(vue实现节流,防止重复提交)