vue 防抖节流,开箱即用
程序员文章站
2022-06-28 18:47:31
vue 防抖节流,开箱即用在util下建个下图文件名将下方代码放到文件中const debounce = (func, time, isDebounce, ctx) => { var timer, lastCall, rtn; //防抖函数 if (isDebounce) { rtn = (...params) => { if (timer) clearTimeout(timer); timer = s...
vue 防抖节流,开箱即用
在util下建个下图文件名
将下方代码放到文件中
const debounce = (func, time, isDebounce, ctx) => {
var timer, lastCall, rtn;
//防抖函数
if (isDebounce) {
rtn = (...params) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(ctx, params);
}, time);
};
} else {//节流函数
rtn = (...params) => {
const now = new Date().getTime();
if (now - lastCall < time && lastCall) return;
lastCall = now;
func.apply(ctx, params);
};
}
return rtn;
};
export default {
name: 'Debounce',
abstract: true,
props: {
time: {
type: Number,
default: 800,
},
events: {
type: String,
default: 'click',
},
isDebounce: {
type: Boolean,
default: false,
},
},
created() {
this.eventKeys = this.events.split(',');
this.originMap = {};
this.debouncedMap = {};
},
render() {
const vnode = this.$slots.default[0];
this.eventKeys.forEach(key => {
const target = vnode.data.on[key];
if (target === this.originMap[key] && this.debouncedMap[key]) {
vnode.data.on[key] = this.debouncedMap[key];
} else if (target) {
this.originMap[key] = target;
this.debouncedMap[key] = debounce(
target,
this.time,
this.isDebounce,
vnode
);
vnode.data.on[key] = this.debouncedMap[key];
}
});
return vnode;
},
};
在main.js文件中导入,使用时按照下方注释放在按钮的外方,设置好时间,设置好是防抖还是节流的参数,即可使用
下面附上使用代码,我这里使用的是防抖,可根据使用情况换成防抖或节流
<Debounce :time='1000' !isDebounce>
<div class="submit" @click="present">提交</div>
</Debounce>
本文地址:https://blog.csdn.net/weixin_45807783/article/details/110131827