一、防抖概念
一定时间段(结束)触发最后次——间隔触发,在执行时间段内被再次触发,则重新计数(清除上一次定时器),类似游戏回城中断,再次回城重新计数,eg:
//初始化定时器
timer: null
//定时器调用函数
this.timer = setTimeout(() => {
this.showLists(this.keyword);
}, 500);
//所被调用函数,清除timer,为下次调用做准备
showLists(keyword) {
clearTimeout(this.timer)
}
二、防抖微项目
项目要求:
仿TaoBao搜索框,输入内容(keyword)搜索框下方显示模糊查询结果,所有显示内容均可跳转,eg:
项目简述:
结果显示框是否显示,V-if(通过length进行判断)
双结果选择(判断)显示,watch监视
获取输入值,@keyup.native
遍历由computed返回列表数据,利用<a>标签跳转,v-for
防抖函数定时器设置,jsonp数据传递函数调用,debounceSearch
keyword传递数据与获取,赋值已定义数组,this.$jsonp
项目代码块:
data模块:
data() {
return {
keyword: "",
suggestionList: {},
cacheList: {}, //cache the data
isShow: false,
timer: null, //timer closed loop
};
},
methods模块:
methods: {
showLists(keyword) {
clearTimeout(this.timer)
if (this.cacheList[keyword]) {
return this.cacheList[keyword];
} else {
this.$jsonp("https://suggest.taobao.com/sug", {
q: keyword,
}).then((res) => {
this.suggestionList = res.result;
// console.log(res);
// console.log(typeof(res.result));
this.cacheList[keyword] = res.result;
});
}
},
// Anti-shaking function
debounceSearch() {
this.timer = setTimeout(() => {
this.showLists(this.keyword);
}, 500);
},
// need the other link
search() {
this.showLists(this.keyword);
},
showSuggestionList() {
this.debounceSearch();
},
},
项目逻辑图:
小白博主一枚,如代码有不足之处,望各位指正(希望生活更加精彩,爱生活~)
节流概念链接:https://blog.csdn.net/Chris__Feng/article/details/128857037
防抖微项目链接:https://github.com/ChrisF1109/Vue-debounce-throttling-.git,位于master分支中