如何在 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(event)
但它似乎不起作用.
With the scrollFunction(event)
being defined in my component methods but it doesn't seem to work.
有人知道怎么做吗?
谢谢!
推荐答案
其实我找到了解决方案.我在创建组件时在 scroll
事件上添加了一个事件监听器,并在组件被销毁时移除了事件监听器.
Actually I found a solution. I add an event listener on the scroll
event when the component is created and remove the event listener when the component is destroyed.
export default {
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll (event) {
// Any code to be executed when the window is scrolled
}
}
}
希望这有帮助!
这篇关于如何在 VueJS 组件中监听窗口滚动事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文