Vue 3 中使用 el-upload 上传文件并获取文件信息
<template>
<el-form>
<el-upload
:action='null'
:auto-upload='false'
:file-list='fileList'
:on-change='handleChange'
>
<el-button type='primary'>Click to upload</el-button>
</el-upload>
<el-form-item>
<el-button type='primary' @click='updateOneSection'>Submit</el-button>
<el-button type='primary' @click='checkForm'>Check</el-button>
</el-form-item>
</el-form>
</template>
<script setup>
import { ref } from 'vue';
const fileList = ref([]);
const handleChange = (file, fileList) => {
// 更新fileList
fileList.value = fileList;
};
const updateOneSection = () => {
// 创建FormData对象
const formData = new FormData();
// 将fileList中的文件添加到formData中
fileList.value.forEach(file => {
formData.append('files[]', file.raw);
});
// 执行提交逻辑,使用formData发送请求或其他操作
// ...
};
const checkForm = () => {
// 执行表单校验逻辑
// ...
};
</script>
<p>在上面的代码中,我们使用<code>ref</code>创建了一个<code>fileList</code>变量,它将被<code>el-upload</code>的<code>file-list</code>属性绑定,并在<code>handleChange</code>方法中更新。然后,我们在<code>updateOneSection</code>方法中创建了一个<code>FormData</code>对象,并将<code>fileList</code>中的文件添加到其中。最后,你可以根据实际需求执行提交逻辑和表单校验逻辑。</p>
原文地址: https://www.cveoy.top/t/topic/qFGe 著作权归作者所有。请勿转载和采集!