用vue3写一个上传图片的组件,显示出选择的图片,可以多选图片,可以删除图片
时间: 2023-05-31 20:03:36 浏览: 128
一个简单的vue上传图片的组件
以下是用Vue3写的上传图片组件,可以选择多个图片并显示出来,可以删除已选图片。
```html
<template>
<div>
<input type="file" ref="input" multiple @change="handleFileChange">
<div v-if="selectedFiles.length > 0">
<div v-for="(file, index) in selectedFiles" :key="index">
<img :src="file.url" alt="Selected Image" width="100">
<button @click="handleRemove(index)">Remove</button>
</div>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'UploadImage',
setup() {
const selectedFiles = ref([]);
const handleFileChange = () => {
const files = Array.from(refs.input.files);
const filePromises = files.map(file => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve({
name: file.name,
url: reader.result
});
reader.onerror = error => reject(error);
})
});
Promise.all(filePromises).then(files => {
selectedFiles.value = [...selectedFiles.value, ...files];
});
};
const handleRemove = index => {
selectedFiles.value.splice(index, 1);
};
return { selectedFiles, handleFileChange, handleRemove };
}
}
</script>
```
使用方式:
```html
<template>
<div>
<upload-image></upload-image>
</div>
</template>
<script>
import UploadImage from './UploadImage.vue';
export default {
components: {
UploadImage
}
}
</script>
```
阅读全文