【问题标题】:Why is removeEventListener not properly working in my Nuxt app?为什么 removeEventListener 在我的 Nuxt 应用程序中无法正常工作?
【发布时间】:2021-10-05 01:56:24
【问题描述】:

当我的应用程序上有搜索结果时,下面的组件会呈现,它会检查用户滚动是否在页面底部。代码起初运行良好,但在导航出页面并返回页面并滚动之后我得到错误

未捕获的类型错误:无法读取未定义的属性“getBoundingClientRect” 在 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>

【问题讨论】:

    标签: javascript node.js vue.js nuxt.js


    【解决方案1】:

    unmounted 是一个 Vue3 生命周期:https://v3.vuejs.org/guide/composition-api-lifecycle-hooks.html

    在 Vue2 中,钩子是 beforeDestroy 和 destroyed,如 API 所示:https://vuejs.org/v2/api/#beforeDestroy

    这是 Vue2 的生命周期图:https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多