I created a Vue form but I'm having trouble making the image preview function work when users try to submit an image to the form.
After refreshing the page, I can see the image, but when uploading it, the preview link is broken. There is an option to remove an image, which works fine, but my goal now is to display an image preview.
<div class="image-block">
<div @click="selectImage('initial-image')">
<img class="img-icon"
v-if="imageName === null">
<div :class="{'error' : errors.length > 0}" class="text-center"
v-if="imageName === null">
Select an image to upload
</div>
</div>
<div class="image-preview" v-if="imageName !== null">
<div class="remove-image" @click="removeImage"><i
class="fa fa-remove"></i>
</div>
<img v-bind:src="'/images/json-ld/images/' + imageName" class="growth-image"
@click="selectImage('initial-image')">
</div>
</div>
<validation-provider name="image" v-slot="{ validate, errors }">
<input type="file" @change="validate" name="image" accept="image/*"
class="hidden"
v-on:change="showFilePreview">
<span class="validation-error form-span">{{ errors[0] }}</span>
</validation-provider>
Methods:
removeImage() {
this.imageName = null;
},
selectImage(id) {
document.getElementById(id).click();
},
showFilePreview(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
Any suggestions on how to make this functionality work as intended?