[这是我第一次使用IntersectionObserver,并且遵循此文档https://www.netguru.com/codestories/infinite-scroll-with-vue.js-and-intersection-observer。但由于此错误,我被屏蔽了
[Vue warn]: Error in mounted hook: "TypeError: Failed to construct 'IntersectionObserver': The provided value is not of type '(Element or Document)'"
这是我的触发器组件
<template>
<span ref='trigger'></span>
</template>
<script>
export default {
props:{
options:{
type: Object,
default: () => ({
root: 0,
threshold: "0",
})
}
},
data(){
return{
observer : null
}
},
mounted(){
this.observer = new IntersectionObserver( entries => {
this.handleIntersect(entries[0]);
}, this.options);
this.observer.observe(this.$refs.trigger);
},
destroyed(){
this.observer.disconnect();
},
methods:{
handleIntersect(entry){
if (entry.isIntersecting) this.$emit("triggerIntersected");
}
}
}
</script>
我该如何解决?(谢谢)
在console.log(this.$refs.trigger)
内运行mounted()
并确保它不是undefined
。
尝试使用querySelectorAll
来获取元素:
<span class="trigger" ref='trigger'></span>
mounted(){
this.observer = new IntersectionObserver(this.observerHandler, this.options)
const elements = document.querySelectorAll('.trigger')
elements.forEach(element => {
this.observer.observe(element)
})
},
destroyed(){
this.observer.disconnect();
},
methods:{
observerHandler(entries, observer) {
for (const entry of entries) {
if (entry.isIntersecting) {
...
}
}
},
handleIntersect(entry){
if (entry.isIntersecting) this.$emit("triggerIntersected");
}
}