【问题标题】:Vue - change URL image path based on screen sizeVue - 根据屏幕大小更改 URL 图像路径
【发布时间】:2021-10-14 13:09:53
【问题描述】:

当我的屏幕尺寸发生变化时,我想更改图像 src。我正在使用 Nuxt。我目前有这个代码:

<div v-for="(item, index) in aside" :key="index"">
   <img :src="item.svgIconDark.filename" />
</div>

这是从 StoryBlok API 调用我的图像。 StoryBlok 包含 2 条路径,我可以将它们用于图像。

在低于中等尺寸的屏幕上,我想显示item.svgIconDark.filename

在中+尺寸的屏幕上,我想显示item.svgIconLight.filename

我也在使用 Tailwind CSS。非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: image vue.js background


    【解决方案1】:

    有两种可能的解决方案。

    1. 显示两个图像并使用 CSS 媒体查询显示/隐藏它们
    <template>
    <div>
      <img src="mobileImage" class="mobile" />
      <img src="desktopImage" class="desktop" />
    </div>
    </template>
    
    <style>
    // I've omitted exact query. try implement the query on your own.
    @media /* mobile query */ {
      img.desktop {
        display: none;
      }
    }
    @media /* desktop query */ {
      img.mobile {
        display: none;
      }
    }
    </style>
    
    1. 订阅调整大小事件并实现显示/隐藏逻辑
    <script>
    export default {
      data: () => ({
        windowSize: 'mobile'
      }),
      beforeMount() {
        window.addEventListener('resize', this.onResize.bind(this))
      },
      beforeDestroy() {
        // don't forget to implement unsubscribe event.
      },
      methods: {
        // when implementing this in production,
        // try wrap this method with debounce method first
        // because there will be users with a REALLY BAD PC out there.
        onResize() {
          if (window.innerWidth >= x) this.windowSize = 'mobile';
          // ...
        }
      }
    }
    </script>
    

    【讨论】:

    • Brillaint,这很完美。它比我想象的要简单。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 2013-05-23
    • 2020-02-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多