Delete/reset a displayed picture from vue js

Viewed 1743

i want to remove image src, here is my template

<div class="file-upload-section">
  <label id="preview" for="file-upload">
      <img v-if="url" :src="url" />
  </label>
  <div class="file-upload">
    <label class="file-upload-button" for="file-upload">Upload Image</label>
    <input type="file" id="file-upload" @change="onFileChange"/>
  </div>
  <div v-if="url">
    <button @click="removeImage()">Remove image</button>
  </div>
</div>

this is my script

data: function () {
    return {
      url: null,
      file: null
    }
  },
  methods: {
    onFileChange (e) {
      this.file = e.target.files[0]
      this.url = URL.createObjectURL(this.file)
    },
    removeImage: function () {
      this.url = null
    }
  }
}

this is all i did, am i doing anything wrong or there is another way to delete a picture from a img

3 Answers

Your code is working; I tried it in my environment. It works perfectly. The issue could be re-rendering. I removed the "file" variable, as this seems no use based on your code, and I created scoped variable inside onFileChange function.

For a re-rendering issue to fix, add the key in your "img" tag and give it a unique value which will change on the "add" and "remove" image. In the below case, I use "URL" as a key.

<img :key="url" v-if="url" :src="url" />

Here is the code, give it a try:

<template>
  <div class="file-upload-section">
    <label id="preview" for="file-upload">
        <img :key="url" v-if="url" :src="url" />
    </label>
    <div class="file-upload">
      <label class="file-upload-button" for="file-upload">Upload Image</label>
      <input type="file" id="file-upload" @change="onFileChange"/>
    </div>
    <div v-if="url">
      <button @click="removeImage()">Remove image</button>
    </div>
  </div>
</template>

<script>
  export default {
    data: function () {
      return {
        url: null
      }
    },
    methods: {
      onFileChange (e) {
        let file = e.target.files[0]
        this.url = URL.createObjectURL(file)
      },
      removeImage: function () {
        this.url = null
      }
    }
  }
</script>

Edit:

On testing your code, I noticed the file preview does reset (the url variable), however the value of the input, did not. I assume that's what you mean, thus:

You can use a ref on the file input, and reset it as well.

Add a ref to your input: <input type="file" id="file-upload" ref="file" @change="onFileChange"/>

Also, update your removeImage method accordingly:

removeImage: function () {
      this.url = ""
      this.$refs.file.value = ""
    }

Pen here

Related