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.handleSubmit = this.throttle(this.handleSubmit, 1000)
  return {
  }
},
methods: {
  handleSubmit() {
    console.log('handleSubmit')
  },
  /**
  * @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)
        }
    }
  }
}

 

 

 

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章