angular.js和vue.js中实现函数去抖示例(debounce)
问题描述
搜索输入框中,只当用户停止输入后,才进行后续的操作,比如发起Http请求等。
学过电子电路的同学应该知道按键防抖。原理是一样的:就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间。本文将分别探讨在angular.js和vue.js中如何实现对用户输入的防抖。
angular.js中解决方案
把去抖函数写成一个service,方便多处调用:
.factory('debounce',['$timeout','$q',function($timeout,$q){
//Theserviceisactuallythisfunction,whichwecallwiththefunc
//thatshouldbedebouncedandhowlongtowaitinbetweencalls
returnfunctiondebounce(func,wait,immediate){
vartimeout;
//Createadeferredobjectthatwillberesolvedwhenweneedto
//actuallycallthefunc
vardeferred=$q.defer();
returnfunction(){
varcontext=this,args=arguments;
varlater=function(){
timeout=null;
if(!immediate){
deferred.resolve(func.apply(context,args));
deferred=$q.defer();
}
};
varcallNow=immediate&&!timeout;
if(timeout){
$timeout.cancel(timeout);
}
timeout=$timeout(later,wait);
if(callNow){
deferred.resolve(func.apply(context,args));
deferred=$q.defer();
}
returndeferred.promise;
};
};
}])
调用方法,在需要使用该功能的controller/directive中注入debounce,也要注入$watch,然后:
$scope.$watch('searchText',debounce(function(newV,oldV){
console.log(newV,oldV);
if(newV!==oldV){
$scope.getDatas(newV);
}
},350));
大功告成!
Vue.js中的解决方案
首先在公共函数文件中注册debounce
exportfunctiondebounce(func,delay){
lettimer
returnfunction(...args){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(()=>{
func.apply(this,args)
},delay)
}
}
然后在需要使用的组件中引入debounce,并且在created生命周期内调用:
created(){
this.$watch('searchText',debounce((newSearchText)=>{
this.getDatas(newSearchText)
},200))
}
大功告成!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下