const options = {
offset: -50
};
export default {
name: 'BarMenu',
data() {
return {
scrollingDirection: '',
}
},
computed: {
cssClasses() {
return {
hidden: this.scrollingDirection === 'down'
}
}
},
mounted() {
this.onScroll();
},
methods: {
scrollToIngredients() {
return this.$scrollTo(document.getElementById('ingredients-inside-content'), 600, options);
},
scrollToRecipes() {
return this.$scrollTo(document.getElementById('similar-recipes'), 600, options);
},
scrollToComments() {
return this.$scrollTo(document.getElementById('comments'), 600, options);
},
onScroll() {
let lastScrollTop = 0;
const handler = () => {
let st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
this.scrollingDirection = 'down';
} else {
this.scrollingDirection = 'up';
}
lastScrollTop = st <= 0 ? 0 : st;
};
window.removeEventListener("scroll", handler, false);
window.addEventListener("scroll", handler, false);
}
},
}
此行不起作用,为什么? window.removeEventListener("scroll", handler, false);
我尝试了所有方法:箭头函数,函数声明等。但是该事件侦听器根本无法删除。
答案 0 :(得分:1)
我遇到了类似的问题,最后,我用另一种方法解决了这个问题,在once
函数的参数中添加了addEventListener
选项,该选项会自动删除它,并且对我有效,以帮助您检查parameters
答案 1 :(得分:0)
似乎您的逻辑有些复杂。就像Bravo在评论中提到的一样,您将需要对处理程序的静态引用以使其解除绑定:您可以简单地将其声明为组件方法。这是更新代码的方法:
onScroll()
方法来处理滚动逻辑。您只需在添加/删除事件侦听器中传递此方法引用lastScrollTop
缓存为组件数据的一部分。
3,然后,您只需在mounted()
生命周期挂钩中添加滚动事件侦听器,然后在destroyed()
生命周期挂钩中将其删除。请参见下面的更新代码:
const options = {
offset: -50
};
export default {
name: 'BarMenu',
data() {
return {
scrollingDirection: '',
lastScrollTop: 0,
}
},
computed: {
cssClasses() {
return {
hidden: this.scrollingDirection === 'down'
}
}
},
mounted() {
window.addEventListener("scroll", this.onScroll, false);
},
destroyed() {
window.removeEventListener("scroll", this.onScroll, false);
},
methods: {
scrollToIngredients() {
return this.$scrollTo(document.getElementById('ingredients-inside-content'), 600, options);
},
scrollToRecipes() {
return this.$scrollTo(document.getElementById('similar-recipes'), 600, options);
},
scrollToComments() {
return this.$scrollTo(document.getElementById('comments'), 600, options);
},
onScroll() {
let st = window.pageYOffset || document.documentElement.scrollTop;
if (st > this.lastScrollTop) {
this.scrollingDirection = 'down';
} else {
this.scrollingDirection = 'up';
}
this.lastScrollTop = st <= 0 ? 0 : st;
}
},
}