問(wèn)題描述

成都創(chuàng)新互聯(lián)是專(zhuān)業(yè)的磐安網(wǎng)站建設(shè)公司,磐安接單;提供成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè),網(wǎng)頁(yè)設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專(zhuān)業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行磐安網(wǎng)站開(kāi)發(fā)網(wǎng)頁(yè)制作和功能擴(kuò)展;專(zhuān)業(yè)做搜索引擎喜愛(ài)的網(wǎng)站,專(zhuān)業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來(lái)合作!
搜索輸入框中,只當(dāng)用戶(hù)停止輸入后,才進(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ì)用戶(hù)輸入的防抖。
angular.js中解決方案
把去抖函數(shù)寫(xiě)成一個(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í)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
分享名稱(chēng):angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce)
網(wǎng)站URL:http://www.chinadenli.net/article28/iehijp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、電子商務(wù)、全網(wǎng)營(yíng)銷(xiāo)推廣、微信公眾號(hào)、虛擬主機(jī)、移動(dòng)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)