Vue 3 el-upload 上传文件获取文件列表并添加到 formData 中
<template>
<el-form>
<el-upload
:action='null'
:auto-upload='false'
:file-list='fileList'
@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, reactive } from 'vue';
const fileList = ref([]);
const formData = reactive({});
const handleChange = (event) => {
fileList.value = Array.from(event.target.files);
// Create a new FormData object
const newFormData = new FormData();
// Append each file to the FormData object
fileList.value.forEach((file) => {
newFormData.append('files[]', file);
});
// Update the formData
Object.assign(formData, newFormData);
};
const updateOneSection = () => {
// Use the formData in your updateOneSection logic
// ...
};
const checkForm = () => {
// Use the fileList and formData in your checkForm logic
// ...
};
</script>
<p>在 <code>handleChange</code> 方法中,我们首先创建一个新的 <code>FormData</code> 对象 <code>newFormData</code>。然后,我们循环遍历 <code>fileList</code>,使用 <code>append</code> 方法将每个文件添加到 <code>newFormData</code> 中。最后,我们使用 <code>Object.assign</code> 方法将 <code>newFormData</code> 的内容复制到 <code>formData</code> 中,以便在其他方法中可以访问到它们。</p>
<p>请注意,上述代码使用了 Vue 3 的 Composition API 中的 <code><script setup></code> 语法,它是 Vue 3 中推荐的新的脚本语法。如果您使用的是 Vue 2,您可以将上述代码放在一个单独的 <code><script></script></code> 标签中,并将 <code>fileList</code> 和 <code>formData</code> 声明为响应式数据。</p>
原文地址: https://www.cveoy.top/t/topic/qFG0 著作权归作者所有。请勿转载和采集!