PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

寻∝梦
寻∝梦 原创
2018-09-07 17:45:03 1486浏览

本篇文章主要的介绍关于angularjs的实现函数,提供了一个关于angularjs的问题和解决方案,现在就让我们一起来看看这篇文章吧

问题描述

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

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

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))
}

大功告成!

引用

1. https://stackoverflow.com/questions/29771011/angularjs-watch-with-debounce
2. https://www.cnblogs.com/fsjohnhuang/p/4147810.html

好了,本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。


以上就是angular.js和vue.js中实现函数去抖(debounce)的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。