Vue - change URL image path based on screen size

Viewed 705

I want to change the image src when my screen size changes. I'm using Nuxt. I have this code currently:

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

that is calling my image from StoryBlok API. StoryBlok holds 2 paths that I can use for the image.

On lower than a medium sized screen, I want to display item.svgIconDark.filename

On a medium + sized screen, I want to display item.svgIconLight.filename.

I am also using Tailwind CSS. Any help greatly appreciated. Thank you.

1 Answers

there are two possible solutions.

  1. display two images and show/hide them with CSS media query
<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. subscribe to resizing event and implement show/hide logic
<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>
Related