Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  151] [ 3]  / answers: 1 / hits: 28709  / 5 Years ago, thu, march 28, 2019, 12:00:00

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?


More From » vue.js

 Answers
3

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 */
}
}

Edit


[#52340] Saturday, March 23, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bobbyallanh

Total Points: 693
Total Questions: 120
Total Answers: 101

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;