I'm new to vue and building a site with a parallax image. The transition between different viewport widths works fine, but I can't get the starting value inside data to the right value, if the initial viewport width is anything other than mobile portrait.
Right now the start value for r_speed (rellax speed) is set to -5 which corresponds to mobile portrait viewport width which is < 576px. When transitioning to a larger viewport the parallax speed is adapted to r_speed = -3.
If I load in the page with any other viewport width though, the initial r_speed is still -5, which in case of >576px produces a suboptimal parallax experience.
How do I set the initial r_speed depending on viewport width? I need something like this:
data() {
if (window.innerWidth >= 576) {
this.r_speed = -3;
return;
}
this.r_speed = -5
}
This is my home vue single page component:
template>
<section id="home">
<h1>Some heading.</h1>
<h2>Some other heading</h2>
<div id="image" v-rellax="{ speed: r_speed }"></div>
</section>
</template>
<script>
export default {
name: "home",
data() {
return {
r_speed: -5
}
},
methods: {
onresize(event) {
if (event.target.innerWidth >= 576) {
this.r_speed = -3;
return;
}
this.r_speed = -5
}
},
created() {
window.addEventListener("resize", this.onresize)
},
beforeDestroy() {
window.removeEventListener("resize", this.onresize)
}
}
</script>
Edit:
I've tried implementing @Nikola's answer in my component:
<script>
export default {
name: "home",
data() {
return {
windowWidth: window.innerWidth,
r_speed: -5
// r_speed: -3
}
},
methods: {
onresize(event) {
if (this.windowWidth >= 576) {
this.r_speed = -3;
return;
}
this.r_speed = -5
}
},
mounted() {
this.$nextTick(() => {
this.onresize()
})
},
created() {
window.addEventListener("resize", this.onresize)
},
beforeDestroy() {
window.removeEventListener("resize", this.onresize, true)
}
}
</script>
The initial r_speed is now correct but the transitions stopped working.