最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce)

 更新時(shí)間:2018年01月18日 08:34:21   作者:anetin  
這篇文章主要介紹了angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

問(wèn)題描述

搜索輸入框中,只當(dāng)用戶停止輸入后,才進(jìn)行后續(xù)的操作,比如發(fā)起Http請(qǐng)求等。

學(xué)過(guò)電子電路的同學(xué)應(yīng)該知道按鍵防抖。原理是一樣的:就是說(shuō)當(dāng)調(diào)用動(dòng)作n毫秒后,才會(huì)執(zhí)行該動(dòng)作,若在這n毫秒內(nèi)又調(diào)用此動(dòng)作則將重新計(jì)算執(zhí)行時(shí)間。本文將分別探討在angular.js和vue.js中如何實(shí)現(xiàn)對(duì)用戶輸入的防抖。

angular.js中解決方案

把去抖函數(shù)寫成一個(gè)service,方便多處調(diào)用:

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

調(diào)用方法,在需要使用該功能的controller/directive中注入debounce,也要注入$watch,然后:

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

大功告成!

Vue.js中的解決方案

首先在公共函數(shù)文件中注冊(cè)debounce

export function debounce(func, delay) {
 let timer

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

然后在需要使用的組件中引入debounce,并且在created生命周期內(nèi)調(diào)用:

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

大功告成!

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

古田县| 青岛市| 平定县| 十堰市| 忻州市| 乌拉特前旗| 永年县| 平乡县| 都安| 吕梁市| 宣武区| 高雄市| 交口县| 屏东市| 东阳市| 房山区| 余庆县| 利川市| 年辖:市辖区| 寿光市| 邢台县| 邻水| 闽侯县| 闻喜县| 富民县| 平湖市| 来安县| 锦州市| 大英县| 东山县| 若羌县| 龙陵县| 怀仁县| 安丘市| 开远市| 梅河口市| 鹤峰县| 呈贡县| 平定县| 绍兴县| 新田县|