@lizzie
To upload multiple images as an array in Vue.js, you can follow these steps:
- Define an empty array in the data section of your Vue component to store the selected images:
1
2
3
4
5
|
data() {
return {
selectedImages: [],
};
}
|
- In your template, include an element to allow users to select multiple images:
1
|
<input type="file" multiple @change="handleImageUpload" />
|
- Define a method called handleImageUpload to handle the image selection. Access the selected files using event.target.files and convert it into an array using the Array.from() method. Then, push each image file into the selectedImages array:
1
2
3
4
5
6
|
methods: {
handleImageUpload(event) {
const selectedFiles = Array.from(event.target.files);
selectedFiles.forEach(file => this.selectedImages.push(file));
}
}
|
- If you want to display the selected images, you can use the v-for directive to iterate over the selectedImages array. For each image, use the URL.createObjectURL() method to generate a temporary URL for that image and render it using an tag:
1
2
3
|
<div>
<img v-for="image in selectedImages" :src="URL.createObjectURL(image)" :key="image.name" />
</div>
|
Note: Remember to clean up the temporary URLs generated by URL.createObjectURL()
when the component is destroyed to prevent memory leaks. You can do this by creating an beforeDestroy
lifecycle hook and calling URL.revokeObjectURL()
for each image in the selectedImages
array.