angular.js和vue.js中實現函數去抖樣本(debounce),vue.jsdebounce

來源:互聯網
上載者:User

angular.js和vue.js中實現函數去抖樣本(debounce),vue.jsdebounce

問題描述

搜尋輸入框中,只當使用者停止輸入後,才進行後續的操作,比如發起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))}

大功告成!

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.