angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce)
問題描述
搜索輸入框中,只當(dāng)用戶停止輸入后,才進(jìn)行后續(xù)的操作,比如發(fā)起Http請求等。
學(xué)過電子電路的同學(xué)應(yīng)該知道按鍵防抖。原理是一樣的:就是說當(dāng)調(diào)用動(dòng)作n毫秒后,才會(huì)執(zhí)行該動(dòng)作,若在這n毫秒內(nèi)又調(diào)用此動(dòng)作則將重新計(jì)算執(zhí)行時(shí)間。本文將分別探討在angular.js和vue.js中如何實(shí)現(xiàn)對用戶輸入的防抖。
angular.js中解決方案
把去抖函數(shù)寫成一個(gè)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)文章
Angular中使用$watch監(jiān)聽object屬性值的變化(詳解)
下面小編就為大家?guī)硪黄狝ngular中使用$watch監(jiān)聽object屬性值的變化(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04
詳解什么是@ngrx/store開發(fā)包中的MemoizedSelector
這篇文章主要為大家介紹了@ngrx/store開發(fā)包中的MemoizedSelector使用分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
使用Angular CLI快速創(chuàng)建Angular項(xiàng)目的一些基本概念和寫法小結(jié)
這篇文章主要介紹了使用Angular CLI快速創(chuàng)建Angular項(xiàng)目的一些基本概念和寫法小結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04
妙用Angularjs實(shí)現(xiàn)表格按指定列排序
使用AngularJS的過濾器,可以很容易的實(shí)現(xiàn)在表格中,點(diǎn)擊某一列標(biāo)題進(jìn)行排序,實(shí)現(xiàn)代碼也很簡單,下面小編給大家分享angularjs實(shí)現(xiàn)表格按指定列排序的實(shí)現(xiàn)代碼,需要的的朋友參考下吧2017-06-06
AngularJS實(shí)現(xiàn)表單驗(yàn)證功能
這篇文章主要為大家詳細(xì)介紹了AngularJS實(shí)現(xiàn)表單驗(yàn)證功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
淺析angularJS中的ui-router和ng-grid模塊
下面小編就為大家?guī)硪黄獪\析angularJS中的ui-router和ng-grid模塊。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-05-05
angularjs自定義ng-model標(biāo)簽的屬性
這篇文章主要介紹了angularjs自定義ng-model標(biāo)簽的屬性的相關(guān)資料,需要的朋友可以參考下2016-01-01

