Hi Everyone, Hope you are doing well and staying safe,
Today I will be sharing with you the small snippet of code that can help you to preview the image the user before it gets uploaded
Create a Directory and File.
mixins/ImagePreviewMixin.vue
<script> export default { data() { return { imagePreviewURL: null, } }, methods: { onFileChange(payload) { //const file = payload.target.files[0]; // use it in case of normal HTML input const file = payload; // in case vuetify file input if (file) { this.imagePreviewURL = URL.createObjectURL(file); URL.revokeObjectURL(file); // free memory } else { this.imagePreviewURL = null } } }, } </script>
We have created the Mixin and we can import that mixin into component
for example
components/UpdateUserAvatar.vue
<script> import ImagePreviewMixin from "@/mixins/ImagePreviewMixin"; export default { mixins: [ImagePreviewMixin], } </script> <template><div> Using Vuetify <v-file-input v-model="avatarImage" label="Image" required @change="onFileChange" ></v-file-input> /* IN case of Normal HTML Input <input v-model="avatarImage" type="file" label="Image" required @change="onFileChange" ></v-file-input> */ <img v-if="imagePreviewURL" :src="imagePreviewURL" alt="" style="max-width: 100%;width: 250px; object-fit: cover" /> </div></template>
Top comments (3)
any preview?
Updated
If someone encounters error try my code : dev.to/cedric_i/vue-js-image-previ...