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

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM