[Vuejs]-VueJS zooms all five images at once

0👍

You will have to abstract them into individual components, or at least declare a zoomed state for each individual image. That is because the this.isZoomed state is stored on the app level where all the images reside in, which means each image does not store its individual zoomed state.

VueJS makes atomic design extremely easy: in this case, your advertis*m*nt image is the atomic component since it should handle its own state. This can be done by creating a custom component, say <ad-image>, that will track the individual isZoomed state of the image, as well as its dimensions:

Vue.component('ad-image', {
  template: '#ad-image',
  props: {
    src: {
      type: String,
      required: true
    }
  },
  data: function() {
    return {
      width: 300,
      height: 300,
      isZoomed: false
    }
  },
  methods: {
    zoomIn() {
      this.isZoomed = true;
      this.width = 300;
      this.height = 300;
    },
    zoomOut() {
      this.isZoomed = false;
      this.width = 100;
      this.height = 100;
    }
  },
  computed: {
    toggleZoom() {
      return this.isZoomed ? this.zoomOut : this.zoomIn;
    }
  }
});

new Vue({
  el: '#advertis*m*ntManagement',
  data: {
    advertis*m*nt: {
      img: 'https://via.placeholder.com/300x300',
      img2: 'https://via.placeholder.com/300x300',
      img3: 'https://via.placeholder.com/300x300',
      img4: 'https://via.placeholder.com/300x300'
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="advertis*m*ntManagement">
  <ad-image :src="advertis*m*nt.img" />
  <ad-image :src="advertis*m*nt.img2" />
  <ad-image :src="advertis*m*nt.img3" />
  <ad-image :src="advertis*m*nt.img4" />
</div>

<script type="text/x-template" id="ad-image">
  <img :src="src" class="mr-3" :style="{ width: width + 'px', height: height + 'px' }" @click="toggleZoom" />
</script>

Pro-tip: you can abstract all style bindings into a computed property, so that you don’t clutter your VueJS template with string interpolations and concatenations:

<img :src="src" class="mr-3" :style="styleObject" @click="toggleZoom" />

And then in your JS logic:

computed: {
  toggleZoom() {
    return this.isZoomed ? this.zoomOut : this.zoomIn;
  },
  styleObject() {
    return {
        width: width + 'px',
        height: height + 'px'
    };
  }
}

Leave a comment