<script setup>
import { ref } from 'vue';

const fileList = ref([]);

const updateOneSection = async () => {
  const formData = new FormData();
  fileList.value.forEach(file => {
    formData.append('file', file.raw);
  });
  console.log(formData);
};

const handleChange = (file, fileList) => {
  fileList.forEach((file, index) => {
    fileList[index].status = 'ready';
  });
  fileList.value = [...fileList]; // 使用展开运算符更新 ref 对象
  console.log(fileList.value);
};
</script>
<template>
  <div class="wrapper">
    <h2 class="formTitle">--块一</h2>
    <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>
  </div>
</template>
<p>根据你提供的代码,问题可能出在以下几个地方:</p>
<ol>
<li>
<p><code>&lt;script setup&gt;</code> 中的 <code>fileList</code> 是一个 ref 对象,但是在 <code>updateOneSection</code> 方法中使用的时候没有解包(即使用 <code>fileList.value</code> 访问),可能导致 <code>formData</code> 中没有正确的数据。你应该在 <code>updateOneSection</code> 方法中使用解包的 <code>fileList.value</code>。</p>
</li>
<li>
<p>在 <code>handleChange</code> 方法中,你使用了 <code>fileList.value = fileList</code> 来更新 <code>fileList</code> 的值。然而,在 Vue 3 中,应该使用 <code>fileList.value = [...fileList]</code> 来更新 ref 对象的值。你可以尝试修改这行代码。</p>
</li>
<li>
<p>在 <code>&lt;el-upload&gt;</code> 组件中,你传递了 <code>:action=&quot;null&quot;</code>,这意味着上传请求将不会发送到任何地址。如果你希望发送上传请求,你需要提供一个正确的上传地址。</p>
</li>
</ol>
<p>请尝试修改以上问题,并重新测试你的代码,看看问题是否解决了。</p>
Vue.js 上传文件 formData 无法获取数据问题解决

原文地址: https://www.cveoy.top/t/topic/qFHS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录