用vue3写一个图片上传
时间: 2023-06-12 11:05:26 浏览: 43
在 Vue 3 中写一个图片上传功能,你需要以下步骤:
1. 在模板中添加一个 HTML 表单,其中包含一个 `<input type="file">` 元素用于选择图片。
2. 为表单元素添加一个 `@change` 事件监听器。这样,当用户选择图片时,你的代码就会收到通知。
3. 在事件监听器中,使用 `FormData` 对象来构建请求体。
4. 使用 `axios` 库发送一个 HTTP POST 请求到服务器,请求体包含刚刚构建的 `FormData` 对象。
5. 在服务器端,使用相应的技术(如 PHP、Node.js 等)来处理图片上传。
以下是一个示例代码:
```
<template>
<form @submit.prevent="uploadImage">
<input type="file" ref="fileInput" @change="handleFileChange" />
<button type="submit">上传</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
methods: {
handleFileChange(event) {
this.file = event.target.files[0];
},
async uploadImage() {
const formData = new FormData();
formData.append('image', this.file);
try {
const response = await axios.post('/api/upload', formData);
console.log(response);
} catch (error) {
console.error(error);
}
}
}
};
</script>
```
这是一个基本的图片上传功能,你可以根据需要对其进行修改和扩展。