开发中需要运用的场景:
1、对提交按钮进行变态的点击压力测试
2、输入框内容的实时校验(譬如验证用户名是否已存在)
3、图片滚动加载scroll操作
4、窗口放大缩小resize操作
5、对某一区域进行mousemove操作
防抖(点击事件为例)
//事件的最后执行(在规定的时间t内,如果连续触发某一事件,则不会调用事件回调函数;连续触发某一事件,t时间内,不再触发该事件,则执行事件回调函数。)
//在公共方法中
export const debounce = function(fn, delay) {
var timer = null;
return function() {
timer && clearTimeout(timer);
var context = this, // 将执行环境指向当前dom
arg = arguments; // 事件e
timer = setTimeout(function() {
fn.call(context, arg);
},delay);
}
}
//在公共方法中引用防抖方法
import debounce from ' '
<button @click="submit">提交</button>
<script>
submit:debounce(()=>{
//调用后台服务
save(obj).then(()={}).ctach((){})
}, 1000));
</script>
//事件的开始执行(点击事件后立即执行,在接下来的连续触发中,不执行事件回调函数)
function debounce(fn, delay, isImmediate) {
var timer = null;
return function() {
timer && clearTimeout(timer);
var context = this, // 将执行环境指向当前dom
arg = arguments; // 事件e
if(isImmediate) {
!timer && fn.call(context, arg); // timer为null(即没有被执行过,或被重置)
// 立即执行,后续连续点击不起作用
timer = setTimeout(function() {
timer = null;
}, delay);
} else {
timer = setTimeout(function() {
fn.call(context, arg);
},delay);
}
}
}
节流(touchmove事件为例)
function throttle(fn, delay) {
var start = new Date();
return function() {
var context = this, // 将执行环境指向当前dom
arg = arguments; // 事件e
var current = new Date();
if(current - start >= delay) {
fn.call(context, arg);
start = current;
}
}
}
在页面中的使用(搜索按钮防抖)
onSearch:debounce(function() {
let params = {
username: this.searchValue,
tenantId: this.userInfo.tenantId
};
pageSearch(
Object.assign(
{
current: this.currentPage,
size: this.pageSize,
},
params
)
).then(response => {
console.log('调服务');
this.list = response.data.data.records;
if (this.list.length == 0) {
this.emptyShow = true;
} else {
this.emptyShow = false;
}
this.total = response.data.data.total;
});
},1000),