vue防抖组件
# vue 防抖组件
export default {
name: 'debounce',
abstract: true,
props: {
time: {
type: Number,
default: 1000
},
throttle: {
type: Boolean,
default: false
},
//defer默认true: 反向防抖,先执行回调,单位时间内重触发时间,不再执行回调。可用于合并请求,执行第一次 后续单位时间内不再执行。
defer:{
type: Boolean,
default: true
}
},
data(){
return {}
},
render() {
//所有的 $slots 现在都会作为函数暴露在 $scopedSlots 中。
const vnode = this.$slots.default ? this.$slots.default[0] : null;
console.log(this.$slots.default)
if (vnode){
let throttledMap = {};
let listeners = vnode.data.on || vnode.componentOptions.listeners;
console.log('listeners',listeners)
console.log('listeners2',Object.getOwnPropertyNames(listeners))
if (listeners){
Object.getOwnPropertyNames(listeners).forEach(key => {
if (!throttledMap[key]){
throttledMap[key] = this.debounce(listeners[key], this.time ,this.defer);
}
console.log('listeners3',key,throttledMap[key])
});
Object.getOwnPropertyNames(throttledMap).forEach(key => {
listeners[key] = throttledMap[key];
})
}
}
return vnode;
},
methods: {
debounce(fn, wait = 300, defer = false) {
let timer, deferTimer;
return function (...args) {
let that = this;
if (timer) {
clearTimeout(timer);
}
if (defer && !deferTimer) {
deferTimer = true;
fn.apply(that, args);
}
timer = setTimeout(() => {
deferTimer = null;
!defer && fn.apply(that, args);
}, wait);
};
}
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
编辑 (opens new window)