首页 > 解决方案 > window.removeEventListener 在 Nuxt JS 中不起作用

问题描述

我已经在 created 钩子中声明了滚动事件侦听器。

created () {
        if (typeof window !== 'undefined') {
            window.addEventListener('scroll', this.handleNavScroll);
        }
},

但是,当我当时移动到另一个 url 时,我试图在 beforeDestroy() 钩子上销毁这个事件侦听器,但它不起作用。

beforeDestroy() {
        console.log('before destroy called ...');
        window.removeEventListener('scroll', this.handleNavScroll)
}

即使我也试图从destroy () 钩子中销毁它,但没有工作,也没有删除它。

destroyed () {
        console.log('destroyed called in home page');
        window.removeEventListener('scroll', this.handleNavScroll)
}

这是我的方法

handleNavScroll() {
        this.scrolled = window.scrollY > 0;

        if(window.scrollY > 150){
            this.navColor = false;
            this.$root.$emit('navbarColorProps', 'black')
            this.$root.$emit('navbarColorMobileProps', 'black')
        }
        if(window.scrollY < 150){
            this.navColor = true;
            this.$root.$emit('navbarColorProps', 'rgba(255,255,255,0.0) !important')
            this.$root.$emit('navbarColorMobileProps', 'rgba(255,255,255,0.0) !important')
        }

}

请帮助我无法删除事件侦听器。

标签: nuxt.jsevent-listenerremoveeventlistener

解决方案


推荐阅读