为什么要使用节流和防抖
我在写商品上拉加载时,重复在数据库拿数据,这时候,就要使用节流和防抖。
在进行窗口的scroll,输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负担,导致用户体验非常糟糕。
此时我们可以采用debounce(防抖)和throttle(节流)的方式来减少调用频率,同时又不影响实际效果。
如何理解防抖
当你点击时,等待2秒后才触发事件,但是当你在2秒内继续点击,就会重新延迟2秒执行。
如何理解节流
当你点击时,在两秒内,多次点击,但是只会执行一次。
如何在vue中使用节流和防抖
创建一个js文件,引用下方代码。
// 防抖
export function _debounce(fn, delay) {
var delay = delay || 200;
var timer;
return function() {
var th = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
timer = null;
fn.apply(th, args);
}, delay);
};
}
// 节流
export function _throttle(fn, interval) {
var last;
var timer;
var interval = interval || 200;
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);
}
}
}
在你要使用的vue页面引入
如:import {_debounce,_throttle} from "../../components/public/public";
最后在methods 里面调用
methods:{
changefield: _throttle(function(_type, index, item) {
//里面写自己要干的什么事情
this.$store.dispatch("reqRecommendShopList",{page:this.page,count:this.count});
}, 2000)
}
changefield是你自己的方法名称,记住要调用。不然不会执行。
2000是你设置的反应时间。文件里面默认的是200毫秒,可自行调整。