-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathObserver.vue
More file actions
56 lines (55 loc) · 1.09 KB
/
Observer.vue
File metadata and controls
56 lines (55 loc) · 1.09 KB
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
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: "observer",
data() {
return {
observer: null
};
},
props: {
root: {
type: [
typeof HTMLElement !== 'undefined' ? [HTMLElement] : Object,
typeof window !== 'undefined' ? window : null
],
default: null
},
rootMargin: {
type: [String, Number],
default: "0px"
},
// 意味着只要有一个target像素出现在root元素中,回调函数将会被执行
threshold: {
type: [Array, Number],
default: 0
}
},
methods: {
unobserve() {
this.observer.unobserve(this.$el);
}
},
mounted() {
const options = {
root: this.root,
rootMargin: this.rootMargin,
threshold: this.threshold
};
this.observer = new IntersectionObserver(entries => {
this.$emit("on-change", entries[0], this.unobserve);
}, options);
this.observer.observe(this.$el);
},
beforeDestroy() {
if (this.observer) {
this.unobserve();
this.observer = null;
}
}
};
</script>