防抖
当用户触发事件时,一定时间内没有再次触发,那么事件函数只会执行一次,如果在时间到来之前又执行了一次,就重新开始
计时。那么也就是只让你在对应的时间内只执行一次事件函数。
怎么在vue中使用呢?
//定义一个防抖函数
function debounce(func, wait=1000) {
let timeout; // 定时器变量
return function(event) {
clearTimeout(timeout); // 每次触发时先清除上一次的定时器,然后重新计时
timeout = setTimeout(()=>{
func.call(this,event)
}, wait); // 指定 xx ms 后触发真正想进行的操作 handler
};
}
//调用方法
methods: {
clean:debounce(function()
{
//将confirmLoading状态改变成true
this.confirmLoading = true;
//这是定时器,在0.7秒后执行任务
setTimeout(() => {
//将visible状态改为false
this.visible = false;
//将confirmLoading状态改为false
this.confirmLoading = false;
//只有在完成列表项小于等于0向时才弹出弹窗
if(this.getDoneLength > 0){
this.$store.commit('cleanDone')
this.$store.commit('intoLocalStore')
return this.$message.success("清除完成");
}else{
return this.$message.warning("嗷呜~~没有已完成的数据哦~~");
}
},700);
}),
}
节流
当用户重复点击,我们就让他在一段时间后再次执行
怎么在vue中使用呢?
//定义一个节流函数
function throttle(fn, interval) {
var last;
var timer;
var interval = interval || 2000;
return function () {
var th = this;
var args = arguments;
var now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn.apply(th, args);
}, interval);
} else {
last = now;
fn.apply(th, args);
}
}
}
//调用方法
methods: {
clean:throttle(function()
{
//将confirmLoading状态改变成true
this.confirmLoading = true;
//这是定时器,在0.7秒后执行任务
setTimeout(() => {
//将visible状态改为false
this.visible = false;
//将confirmLoading状态改为false
this.confirmLoading = false;
//只有在完成列表项小于等于0向时才弹出弹窗
if(this.getDoneLength > 0){
this.$store.commit('cleanDone')
this.$store.commit('intoLocalStore')
return this.$message.success("清除完成");
}else{
return this.$message.warning("嗷呜~~没有已完成的数据哦~~");
}
},700);
}),
}
总结:防抖是将多次执行变为最后一次执行,节流是将多次执行变为每隔一段时间执行
来一个形象的解释,就比如英雄联盟中英雄的技能读条:
防抖:在技能读条的时候再次施放技能就会重新读条
节流:在技能读条的时候再次施放技能,也会在技能读条时间内施放技能
版权属于:Citrons
本文链接:https://www.citrons.cn/vuejs/277.html
转载时须注明出处及本声明