angular.js和vue.js中實現(xiàn)函數(shù)去抖示例(debounce)
問題描述
搜索輸入框中,只當(dāng)用戶停止輸入后,才進行后續(xù)的操作,比如發(fā)起Http請求等。
學(xué)過電子電路的同學(xué)應(yīng)該知道按鍵防抖。原理是一樣的:就是說當(dāng)調(diào)用動作n毫秒后,才會執(zhí)行該動作,若在這n毫秒內(nèi)又調(diào)用此動作則將重新計算執(zhí)行時間。本文將分別探討在angular.js和vue.js中如何實現(xiàn)對用戶輸入的防抖。
angular.js中解決方案
把去抖函數(shù)寫成一個service,方便多處調(diào)用:
.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;
};
};
}])
調(diào)用方法,在需要使用該功能的controller/directive中注入debounce,也要注入$watch,然后:
$scope.$watch('searchText',debounce(function (newV, oldV) {
console.log(newV, oldV);
if (newV !== oldV) {
$scope.getDatas(newV);
}
}, 350));
大功告成!
Vue.js中的解決方案
首先在公共函數(shù)文件中注冊debounce
export function debounce(func, delay) {
let timer
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, delay)
}
}
然后在需要使用的組件中引入debounce,并且在created生命周期內(nèi)調(diào)用:
created() {
this.$watch('searchText', debounce((newSearchText) => {
this.getDatas(newSearchText)
}, 200))
}
大功告成!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于angular6.0實現(xiàn)的一個組件懶加載功能示例
這篇文章主要介紹了基于angular6.0實現(xiàn)的一個組件懶加載功能示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
使用ngView配合AngularJS應(yīng)用實現(xiàn)動畫效果的方法
這篇文章主要介紹了使用ngView配合AngularJS應(yīng)用實現(xiàn)動畫效果的方法,AngularJS是十分熱門的JavaScript庫,需要的朋友可以參考下2015-06-06
解決Angular4項目部署到服務(wù)器上刷新404的問題
今天小編就為大家分享一篇解決Angular4項目部署到服務(wù)器上刷新404的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
AngularJS使用ngOption實現(xiàn)下拉列表的實例代碼
這篇文章主要介紹了AngularJS使用ngOption實現(xiàn)下拉列表的實例代碼的相關(guān)資料,需要的朋友可以參考下2016-01-01

