Implementing image upload preview functionality in Vue.js is a common requirement that can be achieved through several steps. Below, I'll walk you through how to use Vue.js to create a feature that displays a preview image immediately after the user selects a file.
Step 1: Create a Vue Component
First, we need to create a Vue component that includes a file input field and an <img> tag for displaying the preview image.
html<template> <div> <input type="file" @change="previewImage" /> <img v-if="imageUrl" :src="imageUrl" alt="Image Preview" /> </div> </template> <script> export default { data() { return { imageUrl: null }; }, methods: { previewImage(event) { const file = event.target.files[0]; if (file && file.type.startsWith('image/')) { this.imageUrl = URL.createObjectURL(file); } } } }; </script>
Step 2: Explain the Code
1. File Input (<input type="file">)
This input field allows users to select files, primarily image files. By listening to the change event, we can retrieve the selected file.
2. Image Preview (<img>)
Here, Vue's conditional rendering (v-if) is used, so the image is displayed only when imageUrl has a valid value. imageUrl is a reactive data property used to store the image URL.
3. Handling Image Files (previewImage Method)
This method is triggered by the change event of the file input field. First, it checks if the user has selected a valid file and confirms it is an image type. Then, it uses the URL.createObjectURL() method to generate an accessible URL pointing to the image data in memory. This URL is assigned to imageUrl, and Vue's data binding automatically updates the src attribute of the image tag to display the image.
Step 3: Use the Component
You can import and use this component in any parent component of your Vue application. After the user selects an image file, the preview will be immediately displayed on the interface. The key advantage is that it enables local preview without uploading the file to the server, which improves user experience and reduces server load.