首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使Vue.js单页组件中的初始数据值响应?

如何使Vue.js单页组件中的初始数据值响应?
EN

Stack Overflow用户
提问于 2021-08-22 07:30:01
回答 1查看 158关注 0票数 2

我是vue的新手,我用parallax image构建了一个网站。不同viewport widths之间的转换工作正常,但如果初始viewport width不是mobile portrait,则无法将data中的起始值转换为正确的值。

现在,r_speed的起始值被设置为-5,它对应于mobile portrait viewport width,也就是< 576px。当转换到较大的viewport时,视差速度适应于r_speed = -3

不过,如果我用任何其他viewport width加载页面,那么初始的r_speed仍然是-5,在>576px的情况下,这会产生次优的视差体验。

如何根据r_speed设置初始viewport width?我需要这样的东西:

代码语言:javascript
复制
data() {
  if (window.innerWidth >= 576) {
    this.r_speed = -3;
    return;
  }
  this.r_speed = -5
}

这是我的home vue单页组件:

代码语言:javascript
复制
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的答案:

代码语言:javascript
复制
<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现在是正确的,但转换停止工作。

EN

回答 1

Stack Overflow用户

发布于 2021-08-22 08:22:14

试着在挂载钩子处检查viewport width

代码语言:javascript
复制
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)
  }
});
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68879311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档