問題描述
成都創(chuàng)新互聯(lián)是專業(yè)的磐安網(wǎng)站建設(shè)公司,磐安接單;提供成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行磐安網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
搜索輸入框中,只當(dāng)用戶停止輸入后,才進(jìn)行后續(xù)的操作,比如發(fā)起Http請求等。
學(xué)過電子電路的同學(xué)應(yīng)該知道按鍵防抖。原理是一樣的:就是說當(dāng)調(diào)用動(dòng)作n毫秒后,才會執(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í)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。