[Vuejs]-Image preview disappear while editing the other form value in VueJs

1👍

When I put your component into a playground, everything seems to work. Please confirm that the error does not occur there.

You can adjust the playground until it reproduces the error and then add it to your question. Until we can actually see the error, there is nothing we can do for you.


As you requested, here is how you could build the image preview without using ref. Instead of putting the data URLs into the img tags through $refs, the data URLs are written to a regular data array and then used directly in the v-for. I have also moved it into its own component, so it does not clutter the other already huge component:

const ImagePreviewsComponent = {
  props: ['images'],
  template: `
  <div class="bg-light mt-4 w-50 row">
    <div class="file-listing col-6" v-for="(dataUrl, key) in imagePreviews" :key="key">
      <img :src="dataUrl" class="w-100"/>
    </div>
  </div>
  `,
  data() {
    return {
      imagePreviews: [],
    };
  },
  watch: {
    images: {
      async handler(){
        this.imagePreviews = []
        const promises = [...this.images].map(image => this.loadImagePreview(image))
        this.imagePreviews = await Promise.all(promises)
      },
      immediate: true,
    }
  },
  methods: {
    async loadImagePreview(image){
      const reader = new FileReader()
      const promise = new Promise(resolve => reader.onload = resolve)
      reader.readAsDataURL(image)
      await promise
      return reader.result
    }
  }
}

new Vue({
  el: '#app',
  components: {'image-previews': ImagePreviewsComponent},
  data() {
    return {
      images: [],
    };
  },
})
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
<div id="app" class="m-2">

  <div class="form-group col-md-6 col-xl-4">
    <div class="custom-file">
      <input
        multiple="true"
        type="file"
        @change="e => images = e.target.files ?? e.dataTransfer.files"
      />
    </div>
    
    <image-previews :images="images"></image-previews>

  </div>

</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.10/vue.min.js"></script>

Here it is in the playground from before.

Leave a comment