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