观察 Vuejs 中 window.scrollY 的变化 [英] Watch window.scrollY changes in Vuejs
问题描述
我有一个非常简单的应用程序,它有 2 个组件:App.vue
和另一个组件 Home.vue
,我在其中保存了其余的结构应用程序:一个粘性标题和一些带有可滚动到的锚点的部分.
我想对粘性标题应用一个类,以在滚动页面时最小化徽标.所以我想我会注意 window.scrollY
中的任何变化.因此,如果 scrollY
大于 0,则应用一些最小化徽标的类.
我尝试在我的组件中监听滚动事件,但这并没有走多远.在这里的这个讨论中,提供了一个非常好的解决方案,但我不知道在哪里放置滚动事件.
I have a very simple app, that has 2 components: the App.vue
and another component, Home.vue
where I hold the rest of the structure of the app: a sticky header and some sections with anchors to scroll to.
I want to apply a class to the sticky header to minimize the logo while the page is scrolled. So I thought I'd watch for any changes in window.scrollY
. So if scrollY
is greater than 0, apply some class that minimizes the logo.
I tried to listen to scroll events in my component, but that didn't go very far. In this discussion here, a very good solution is provided, but I don't know where to place the scroll event. https://github.com/vuejs/Discussion/issues/324
So, I thought the most fitting solution would be to create a data property, assign it the window.scrollY
figure and then watch for changes in its value. Unfortunately, the watcher is never triggered. So now I'm stuck. The code is:
data () {
return {
...
windowTop: window.top.scrollY
}
}
...
watch: {
windowTop: {
immediate: true,
handler (newVal, oldVal) {
console.log(newVal, oldVal);
},
}
}
Any ideas of what I might be doing wrong?
window
properties can't be used reactively like that. Instead, you'd have to listen to the window
's scroll
event and respond accordingly:
mounted() {
window.addEventListener("scroll", this.onScroll)
},
beforeDestroy() {
window.removeEventListener("scroll", this.onScroll)
},
methods: {
onScroll(e) {
this.windowTop = window.top.scrollY /* or: e.target.documentElement.scrollTop */
}
}
这篇关于观察 Vuejs 中 window.scrollY 的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!