DDR爱好者之家 Design By 杰米
问题描述
搜索输入框中,只当用户停止输入后,才进行后续的操作,比如发起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)) }
大功告成!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米
暂无评论...
更新日志
2024年04月26日
2024年04月26日
- 群星《发烧混声金唱盘》3CD[MP3][481M]
- DominikWagner-DoubleBassRhapsody(2023)[24-48]FLAC
- 和平之月系列PMR-0048贾鹏芳《浪漫Roman》[WAV+CUE]
- 和平之月系列PMR-0063贾鹏芳二胡《月光Moonlight》[WAV+CUE]
- 黄乙玲.1992-悲恋梦【歌林】【WAV+CUE】
- 许巍.2001-我只有两天精丫红星生产社】【WAV+CUE】
- 王芷蕾.2001-盛开精选2辑【华纳】【WAV+CUE】
- 群星.2003-LOVE情歌集【正东】【WAV+CUE】
- 张其萍《美丽中国梦》[WAV+CUE]
- 群星《嗨麦顶级中文舞曲·金牌舞曲精逊2CD[WAV分轨]
- 群星《发烧女生 DSD》[WAV+CUE][625M]
- 张学友《私人珍藏(黑胶CD)》2CD[WAV+CUE][1.2G]
- 刘紫玲《紫音幽韵(DSD)》[WAV+CUE][441M]
- 刘珺儿.2004-靓人靓歌5CD【音乐谷】【WAV+CUE】
- 康乔.1991-精丫丽风】【WAV+CUE】