[英]How to make initial data value in Vue.js single page component responsive?
我是vue
的新手,正在構建一個帶有parallax image
的網站。 不同viewport widths
之間的過渡效果很好,但如果初始viewport width
不是mobile portrait
,我無法將data
中的起始值設置為正確的值。
現在r_speed
(rellax speed) 的起始值設置為-5
,對應於< 576px
的mobile portrait viewport width
。 當過渡到更大的viewport
時,視差速度會調整為r_speed = -3
。
如果我在頁面中加載任何其他viewport width
,初始r_speed
仍然是-5
,在>576px
的情況下會產生次優的視差體驗。
如何根據viewport width
設置初始r_speed
? 我需要這樣的東西:
data() {
if (window.innerWidth >= 576) {
this.r_speed = -3;
return;
}
this.r_speed = -5
}
這是我的home
vue 單頁組件:
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>
編輯:
我嘗試在我的組件中實現@Nikola 的回答:
<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>
初始r_speed
現在是正確的,但轉換停止工作。
嘗試檢查安裝掛鈎處的viewport width
:
new Vue({ el: '#app', data() { return { windowWidth: window.innerWidth, r_speed: null } }, methods: { onresize(event) { if (this.windowWidth >= 576) { this.r_speed = -3; return; } this.r_speed = -5 } }, created() { this.onresize() window.addEventListener("resize", this.onresize) }, beforeDestroy() { window.removeEventListener("resize", this.onresize) } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <p>r_speed: {{ r_speed }}</p> <section id="home"> <h1>Some heading.</h1> <h2>Some other heading</h2> <div v-if="r_speed" id="image" v-rellax="{ speed: r_speed }"></div> </section> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.