有的時候網速不好,或者使用者習慣不好的時候喜歡輕按兩下按鈕,就會造成表單重複送出多次,看下圖
然後添加了個節流函數,這樣在短時間内點選的話,隻會執行一次,上代碼:
/**
* 節流函數 在規定的時間内請求函數的次數
* @param fn 需要執行的方法
* @param interval 執行的間隔時間
*/
export function _throttle(fn, interval) {
let last = 0
let timer
const interVal = interval || 200
return function() {
const th = this
const args = arguments
const now = new Date().getTime()
if (last && now - last < interVal) {
clearTimeout(timer)
timer = setTimeout(function() {
last = new Date().getTime()
// fn.apply(th, args)
}, interVal)
} else {
last = new Date().getTime()
fn.apply(th, args)
}
}
}
<el-button type="primary" @click="clickCount">點選</el-button>
methods: {
clickCount: _throttle(function() {
console.log(1)
}, 1000)
}