温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

angular.js和vue.js中实现函数去抖示例(debounce)

发布时间:2020-09-14 15:38:56 来源:脚本之家 阅读:145 作者:anetin 栏目:web开发

问题描述

搜索输入框中,只当用户停止输入后,才进行后续的操作,比如发起Http请求等。

学过电子电路的同学应该知道按键防抖。原理是一样的:就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用此动作则将重新计算执行时间。本文将分别探讨在angular.js和vue.js中如何实现对用户输入的防抖。

angular.js中解决方案

把去抖函数写成一个service,方便多处调用:

.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;
   };
  };
 }])

调用方法,在需要使用该功能的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

export function debounce(func, delay) {
 let timer

 return function (...args) {
  if (timer) {
   clearTimeout(timer)
  }
  timer = setTimeout(() => {
   func.apply(this, args)
  }, delay)
 }
}

然后在需要使用的组件中引入debounce,并且在created生命周期内调用:

created() {
 this.$watch('searchText', debounce((newSearchText) => {
  this.getDatas(newSearchText)
 }, 200))
}

大功告成!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI