4👍
Vue attaches watchers to all your data properties inside the component (the state), which also keep track of where it is used.
Vue doesn’t attach a watcher to window
variables. It only does that for its data, and computed properties. Due to this reason, your window.scrollY
watcher is never called.
Your previous solution was correct when you were listening for the change on resize.
1👍
Instead watch
you can use computed
to return your conditions directly like this
export default {
data() {
return {}
},
computed: {
displayedNav: function() {
if(this.$route.params.id){
return false;
else {
return true;
}
},
minimizedNav: function() => {
if(window.scrollY > 500) {
return false;
} else {
return true;
}
}
}
}
In your template use the computed property like this.
<nav class="navbar u-no-padding"
v-if="displayedNav"
:class="minimizedNav ? 'navbar__not-collapsed' : 'navbar__collapsed'">
Vuejs advices to use computed over watch wherever possible
When you have some data that needs to change based on some other data,
it is tempting to overusewatch
– especially if you are coming from an
AngularJS background. However, it is often a better idea to use a
computed
property rather than an imperativewatch
callback
https://v2.vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property