搜尋輸入框中,只當使用者停止輸入後,才進行後續的操作,例如發起Http請求等。
學過電子電路的同學應該知道按鍵防手震。原理是一樣的:就是說當呼叫動作n毫秒後,才會執行該動作,若在這n毫秒內又調用此動作則將重新計算執行時間。本文將分別探討在angular.js和vue.js中如何實現對使用者輸入的防手震。 (想看更多就到PHP中文網AngularJS開發手冊中學習)
把去抖函數寫成一個service,方便多處呼叫:
.factory('debounce', ['$timeout','$q', function($timeout, $q) { // The service is actually this function, which we call with the func // that should be debounced and how long to wait in between calls return function debounce(func, wait, immediate) { var timeout; // Create a deferred object that will be resolved when we need to // actually call the func var deferred = $q.defer(); return function() { var context = this, args = arguments; var later = function() { timeout = null; if(!immediate) { deferred.resolve(func.apply(context, args)); deferred = $q.defer(); } }; var callNow = immediate && !timeout; if ( timeout ) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } return deferred.promise; }; }; }])
呼叫方法,在需要使用該功能的controller/directive中註入debounce,也要注入$watch,然後:
$scope.$watch('searchText',debounce(function (newV, oldV) { console.log(newV, oldV); if (newV !== oldV) { $scope.getDatas(newV); } }, 350));
大功告成!
首先在公共函數檔案中註冊debounce
export function debounce(func, delay) { let timer return function (...args) { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { func.apply(this, args) }, delay) } }
然後在需要使用的元件中引入debounce,並且在created生命週期內呼叫:
created() { this.$watch('searchText', debounce((newSearchText) => { this.getDatas(newSearchText) }, 200)) }
大功告成!
引用
1. https://stackoverflow.com/questions/29771011/angularjs-watch-with-debounce 2. https://www.cnblogs.com/fsjohnhuang/p/4147810.html
好了,這篇文章到這就結束了(想看更多就到PHP中文網AngularJS使用手冊中學習),有問題的可以在下方留言提問。
以上是angular.js和vue.js中實作函數去抖(debounce)的詳細內容。更多資訊請關注PHP中文網其他相關文章!