Basically, what I need is a computed property that returns true
when the window.innerwidth
is equal or lower than 768px and false
when it's higher than 768px.
What I did:
computed: {
isMobile() {
if (window.innerWidth <= 768) {
return true
}
return false
}
}
But that computes that property only once, and if I resize the window later, it doesn't react to that change. What can I do?
The Basics of Vue Reactivity Simply put, a computed property's dependencies are the reactive values that help the property that determine the value that is returned. If none of these change, then, again, the cached value will be returned. If no reactive dependency is changed, a computed property is not recalculated.
Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.
Add an eventlistener to the window like so:
new Vue({
el: "#app",
data() { return { windowWidth: window.innerWidth } },
mounted() {
window.addEventListener('resize', () => {
this.windowWidth = window.innerWidth
console.log(this.isMobile)
})
},
computed: {
isMobile() {
return this.windowWidth <= 768
}
}
})
Computed properties are only updated when their depedencies change, therefore here isMobile won't be reactive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With