Vue js image upload preview; Through this tutorial, i am going to guide you how show image preview before upload in vue js.
Vue JS Image Upload with Preview
Just follow the following steps and display image preview before upload in vue Js app:
- Step 1 – Create New VUE JS App
- Step 2 – Create Image Preview Component
- Step 3 – Import Component on App.vue
Step 1 – Create New VUE JS App
In this step, open your terminal and execute the following command to create new vue js app:
vue create vue-image-upload-preview
Step 2 – Create Image Preview Component
Go to /src/components directory and create a new component called file-preview.vue and add the following code into it:
<template> <div> <div class="imagePreviewWrapper" :style="{ 'background-image': `url(${previewImage})` }" @click="selectImage"> </div> <input ref="fileInput" type="file" @input="pickFile"> </div> </template> <script> export default { data() { return { previewImage: null }; }, methods: { selectImage () { this.$refs.fileInput.click() }, pickFile () { let input = this.$refs.fileInput let file = input.files if (file && file[0]) { let reader = new FileReader reader.onload = e => { this.previewImage = e.target.result } reader.readAsDataURL(file[0]) this.$emit('input', file[0]) } } } } </script> <style scoped lang="scss"> .imagePreviewWrapper { width: 250px; height: 250px; display: block; cursor: pointer; margin: 0 auto 30px; background-size: cover; background-position: center center; } </style>
Step 3 – Import Component on App.vue
Go to /src/ directory and App.vue file. And then add the following code into it:
<template> <FilePreview></FilePreview> </template> <script> import FilePreviewfrom './components/FilePreview'; export default { components: { FilePreview } } </script>
Conclusion
Vue js image upload with preview example. In this tutorial, you have learned how display image preview before upload in vue js.
Be First to Comment