>  기사  >  웹 프론트엔드  >  angular.js 및 vue.js에서 함수 디바운스 구현

angular.js 및 vue.js에서 함수 디바운스 구현

寻∝梦
寻∝梦원래의
2018-09-07 17:45:031792검색

이 글은 주로 angularjs의 구현 기능을 소개하고, Anglejs에 대한 문제점과 해결책을 제시합니다. 이제 이 글을 함께 살펴보도록 하겠습니다.

문제 설명

검색 입력 상자에, 뒤에만 있습니다. 사용자가 입력을 중지하면 HTTP 요청 시작과 같은 후속 작업이 수행됩니다.

전자회로를 공부한 학생들은 버튼 흔들림 방지에 대해 알아야 합니다. 원칙은 동일합니다. 즉, 액션이 n 밀리초 내에 호출되면 해당 액션이 실행됩니다. 이 n 밀리초 내에 액션이 다시 호출되면 실행 시간이 다시 계산됩니다. 이 기사에서는angular.js와 vue.js에서 각각 사용자 입력의 흔들림 방지를 달성하는 방법에 대해 설명합니다. (자세한 내용을 보려면 PHP 중국어 웹사이트AngularJS 개발 매뉴얼을 방문하여 학습하세요.)

angular.js의 솔루션

다중 호출을 용이하게 하는 서비스로 디바운스 기능을 작성하세요.

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

Call 메서드를 사용하세요. 필요할 때 사용하세요. 이 함수의 컨트롤러/지시문에 디바운스를 삽입하고 $watch도 삽입한 다음:

$scope.$watch('searchText',debounce(function (newV, oldV) {
   console.log(newV, oldV);
   if (newV !== oldV) {
       $scope.getDatas(newV);
   }
}, 350));

완료되었습니다!

Vue.js의 솔루션

먼저 공개 함수 파일에 디바운스를 등록하세요

export function debounce(func, delay) {
  let timer

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

그런 다음 사용해야 하는 구성 요소에 디바운스를 도입하고 생성된 라이프 사이클에서 호출하세요.

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에서 함수 디바운스 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.