如何在VueJS组件中监听窗口滚动事件? [英] How to listen to the window scroll event in a VueJS component?
本文介绍了如何在VueJS组件中监听窗口滚动事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想听听Vue组件中的窗口滚动事件。以下是我到目前为止尝试的内容:
I want to listen to the window scroll event in my Vue component. Here is what I tried so far:
<my-component v-on:scroll="scrollFunction">
...
</my-component>
定义 scrollFunction(事件)
在我的组件方法中,它似乎不起作用。
With the scrollFunction(event)
being defined in my component methods but it doesn't seem to work.
任何人都知道如何做到这一点?
Anyone has any idea how to do this?
谢谢!
推荐答案
实际上我找到了一个解决方案。我在创建组件时在滚动
事件上添加了一个事件监听器。此外,请确保在销毁组件时删除事件侦听器。
Actually I found a solution. I add an event listener on the scroll
event when the component is created. Also, be sure to remove the event listener when the component is destroyed.
export default {
methods: {
handleScroll (event) {
// Any code to be executed when the window is scrolled
}
},
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
}
}
希望这会有所帮助!
这篇关于如何在VueJS组件中监听窗口滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文