angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce)
問(wèn)題描述
搜索輸入框中,只當(dāng)用戶停止輸入后,才進(jìn)行后續(xù)的操作,比如發(fā)起Http請(qǐng)求等。
學(xué)過(guò)電子電路的同學(xué)應(yīng)該知道按鍵防抖。原理是一樣的:就是說(shuō)當(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)對(duì)用戶輸入的防抖。
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ù)文件中注冊(cè)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))
}
大功告成!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于angular6.0實(shí)現(xiàn)的一個(gè)組件懶加載功能示例
這篇文章主要介紹了基于angular6.0實(shí)現(xiàn)的一個(gè)組件懶加載功能示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Angular Module聲明和獲取重載實(shí)例代碼
這篇文章主要介紹了Angular Module聲明和獲取重載實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-09-09
使用ngView配合AngularJS應(yīng)用實(shí)現(xiàn)動(dòng)畫效果的方法
這篇文章主要介紹了使用ngView配合AngularJS應(yīng)用實(shí)現(xiàn)動(dòng)畫效果的方法,AngularJS是十分熱門的JavaScript庫(kù),需要的朋友可以參考下2015-06-06
Angular2表單自定義驗(yàn)證器的實(shí)現(xiàn)
本文給大家介紹angular2表單自定義驗(yàn)證器的實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧2016-10-10
解決Angular4項(xiàng)目部署到服務(wù)器上刷新404的問(wèn)題
今天小編就為大家分享一篇解決Angular4項(xiàng)目部署到服務(wù)器上刷新404的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
AngularJS使用ngOption實(shí)現(xiàn)下拉列表的實(shí)例代碼
這篇文章主要介紹了AngularJS使用ngOption實(shí)現(xiàn)下拉列表的實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2016-01-01

