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
<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>
Advertisement
Answer
unmounted is a Vue3 lifecycle: 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
Here is the lifecycle diagram for Vue2: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
