[英]Why is removeEventListener not properly working in my Nuxt app?
The component below renders when there is a search result on my app, and it checks if the user scrolling is at the bottom of the page.当我的应用程序上有搜索结果时,下面的组件会呈现,它会检查用户滚动是否在页面底部。 The code works well at first, but after navigating out of the page and returning back to the page and scrolling is where I then get the error
代码起初运行良好,但是在导航出页面并返回页面并滚动之后,我得到了错误
Uncaught TypeError: Cannot read property 'getBoundingClientRect' of undefined at VueComponent.handleScroll
未捕获的类型错误:无法读取 VueComponent.handleScroll 处未定义的属性“getBoundingClientRect”
<template>
<div class="grid-card-layout scrolling-component" ref="scrollComponent">
<slot/>
</div>
</template>
<script>
export default {
methods: {
handleScroll() {
let element = this.$refs.scrollComponent
if (element.getBoundingClientRect().bottom < window.innerHeight) {
window.removeEventListener('scroll', this.handleScroll);
return this.$emit("load-more");
}
},
mountOnScroll() {
window.addEventListener('scroll', this.handleScroll);
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll);
// Start observing the target node for configured mutations
const observer = new MutationObserver(this.mountOnScroll);
observer.observe(this.$refs.scrollComponent, {
attributes: true,
childList: true,
characterData: true
});
},
unmounted() {
window.removeEventListener('scroll', this.handleScroll);
}
}
</script>
unmounted
is a Vue3 lifecycle:https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html unmounted
是一个 Vue3 生命周期:https ://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html
In Vue2, the hooks are beforeDestroy
and destroyed
as shown in the API: https://v2.vuejs.org/v2/api/#beforeDestroy在 Vue2 中,钩子是
beforeDestroy
并被destroyed
,如 API 所示: https ://v2.vuejs.org/v2/api/#beforeDestroy
Here is the lifecycle diagram for Vue2: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram这是 Vue2 的生命周期图: https ://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.