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)
        }
    }
  }
}

 

 

 

 

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