国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

angular.js和vue.js中實現函數去抖示例(debounce)

2024-05-06 15:22:36
字體:
來源:轉載
供稿:網友

問題描述

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

大功告成!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 洪雅县| 沁阳市| 宝鸡市| 福海县| 东莞市| 七台河市| 平湖市| 密云县| 米脂县| 茂名市| 满城县| 商洛市| 唐山市| 曲麻莱县| 宁夏| 班戈县| 德令哈市| 枝江市| 太仓市| 商南县| 珠海市| 宁陕县| 台南市| 平定县| 江安县| 五华县| 江阴市| 隆安县| 贵阳市| 临夏市| 荥阳市| 且末县| 水城县| 平乐县| 额敏县| 桦川县| 福清市| 安顺市| 太保市| 泰顺县| 阆中市|