vue 中實現 節流函數
fnThrottle(method, delay, duration) { var that = this; var timer = this.timer; var begin = new Date().getTime(); return function() { var current = new Date().getTime(); clearTimeout(timer); if (current - begin >= duration) { method(); begin = current; } else { that.timer = setTimeout(function() { method(); }, delay); } }; },
須在data中定義一個timer
如何使用:
我的需求是在輸入框中輸入時,帶出搜索的結果,實時展示出來
所以我在watch中監聽了輸入框綁定的值
watch: { searchVal(newValue) { this.searchVal = newValue; //在這里調用,並執行 this.fnThrottle(this.search, 500, 2000)(); } }
methods:{ search(){ //請求函數 } }
這樣就實現的在vue中的函數節流。
歡迎大家的指正。