ytsejam
ytsejam

Reputation: 3439

How to use view different images in vue template according to screen resolution?

I am quite new to develop sites using VueJs, I want to learn what is the best way to choose images according to screen resolution. I made lots of research but as keywords are quite common I always come up with how to use width of image. I tried a solution like below but does not seem to work for vuejs.

<template>
<div class="img-wrap">
    <div v-if="!isMobile()">
       <img src="@/assets/img/yogavidya-logo.png" alt="Yogavidya" class="logo-colored">
    </div>
    <div v-else>
       <img src="@/assets/img/logo-small.png" alt="Yogavidya" class="logo-colored">
     </div>
</div>
</template>
<script>
methods:{
    isMobile() {
       if( screen.width <= 760 ) {
            return true;
        }
        else {
            return false;
        }
     }
    }
</script>

How can I make it work for Vue ?

Thanks

Upvotes: 1

Views: 672

Answers (1)

logee
logee

Reputation: 5067

I got inspiration from this article Reactive Window Parameters in VueJS to create a reactive window

Create a 'VueWindow'

import Vue from "vue";

const vueWindow = new Vue({
  data() {
    return {
      innerWidth: 0
    };
  },
  created() {
    this.innerWidth = window.innerWidth;
    window.addEventListener('resize', () => {
      this.innerWidth = window.innerWidth;
    });
  },
  computed: {
    isMobile() {
      return this.innerWidth <= 760;
    }
  }
});

export default vueWindow;

And change the component in the OP to use this window:

<template>
<div class="img-wrap">
    <!-- isMobile is now a computed property -->
    <div v-if="!isMobile">
       <img src="@/assets/img/yogavidya-logo.png" alt="Yogavidya" class="logo-colored">
    </div>
    <div v-else>
       <img src="@/assets/img/logo-small.png" alt="Yogavidya" class="logo-colored">
     </div>
</div>
</template>
<script>
import VueWindow from "./VueWindow";

...
computed: {
    isMobile() {
        return VueWindow.isMobile;
    }
}
...
</script>

Upvotes: 1

Related Questions