[Vuejs]-I want display image in vue3 page before save to database, but my code not working

0👍

There’s multiple things wrong with this code. First off, the "form" variable is not declared anywhere. This should show up in the console.

Second off, you cannot set a method to the src attribute of an image.

You need a ref variable holding the base64 of your image, like;

import { ref } from "vue";

...

const uploadedImageBase64 = ref();

Then, you need to change the base64 when you upload an image;

const changePhoto = (e) => {
  let file = e.target.files[0];
  let reader = new FileReader();
  let limit = 1024*1024*2

  if (file['size'] > limit){
    return false
  }
  reader.onloadend = (file) => {
    //Change this line
    uploadedImageBase64.value = reader.result
  }
  reader.readAsDataURL(file)
}

In the template you can then show this data as follows;

<img v-if="uploadedImageBase64" :src="`${uploadedImageBase64}`" />

Don’t forget to remove all references to the non-existent "form" variable.

You can see it working here:

Demo

Leave a comment