【问题标题】:How to change style of an element based on window width in Vue如何在Vue中根据窗口宽度更改元素的样式
【发布时间】:2021-01-02 20:58:56
【问题描述】:

当窗口大小小于 500 像素时,我正在尝试更改 HTML 元素的样式。目前我有一个计算属性,它定义了元素的背景图像。我尝试在计算属性中使用 if 语句来检查 window.innerWidth

感谢任何帮助。谢谢!

<template>
  <div class="hero" :style="bgImage">
</template
data() {
    return {
      window: {
        width: 0
      }
    }
  },
  created() {
    window.addEventListener('resize', this.handleResize)
    this.handleResize()
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      if (window.width < 500) {
        this.bgImage = `backgroundImage: linear-gradient(to bottom,rgba(245, 246, 252, 0) 45%,rgb(0, 0, 0) 100%), url(${this.hero.image})`
      }
    }
  },
  computed: {
    bgImage() {
      return {
        backgroundImage: `url(${this.hero.image})`
      }
    }
  }

【问题讨论】:

  • 您可以在计算属性中执行逻辑,但它们仅对 Vue 控件的更改做出反应,其中不包括 window
  • 为了使用您的 handleResize 方法,bgImage 应该是 data 属性,而不是计算的。 hero.image 也应该在某处定义
  • 您是否有理由不能使用普通的旧 CSS 媒体查询来处理这个问题?
  • @Phil 我正在将来自 hero 的数据作为道具传递。我会使用常规的 CSS 媒体查询,但由于我正在循环浏览图像,因此我需要一种动态的方式来访问不断变化的图像。

标签: javascript vue.js sass vue-component


【解决方案1】:

尝试使用computed 检查您的width 数据更改。

我这样修改了你的代码

export default {
  data() {
    return {
      window: {
        width: 0,
      },
    },
    computed: {
      bgImage() {
        if (this.width < 500) {
          return {
            backgroundImage: `linear-gradient(to bottom,rgba(245, 246, 252, 0) 45%,rgb(0, 0, 0) 100%), url(${this.hero.image})`
          }
        } else {
          return {
            backgroundImage: `url(${this.hero.image})`
          }
        }
      }
    }

    created: function() {
        window.addEventListener('resize', this.handleResize);
      },
      destroyed: function() {
        window.removeEventListener('resize', this.handleResize);
      },
      methods: {
        handleResize() {
          this.width = window.innerWidth;
        }
      },
  };

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 2017-04-15
    • 2021-12-19
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多