You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何通过FormData传递数组到Laravel后端?

问题原因

你触发报错的直接原因是createCourse方法里硬编码了数组下标sections[1]:

  • JavaScript数组下标从0开始计数,初始化时sections数组只有1个元素,对应下标是0,只有用户点击过至少1次「Add Section」按钮才会生成下标为1的元素,用户没点的情况下访问sections[1]自然会报undefined错误。

除此之外你的代码还有两处明显逻辑错误:

  1. 作用域错误:createCourse函数被定义在uploadFile函数内部,模板中无法正常调用该方法
  2. 提交逻辑缺失:没有遍历完整的sections数组提交所有章节、子章节和对应上传的文件,无法满足你提交包含子章节的章节数组的需求

修复方案

调整代码逻辑

修正函数作用域,遍历所有章节组装FormData,不要硬编码数组下标,修改后的逻辑代码如下:

export default {
  name: 'CreateCourse',
  setup(){
      const sections = reactive([{'section_title': '', 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]]);
      const course = reactive({'title': '', 'description': ''});
      const {showLoader} = magicFunction();

      const addSection = () => {
          sections.push({"section_title": "", 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]});
      }
      const addSubSection = (idx) => {
          sections[idx].sub_sections.push({"sub_section_title": "", 'file': '', 'url': ''});
      }

      const uploadFile = (e, idx, i) => {
          sections[idx].sub_sections[i].file = e.target.files[0];
          sections[idx].sub_sections[i].url = URL.createObjectURL(sections[idx].sub_sections[i].file);
      }

      const createCourse = (e) => {
          const formData = new FormData();
          formData.append("course[title]", course.title);
          formData.append("course[description]", course.description);

          // 遍历所有章节组装数据,兼容任意数量的章节/子章节
          sections.forEach((section, sectionIndex) => {
              formData.append(`sections[${sectionIndex}][section_title]`, section.section_title);
              // 遍历当前章节下的所有子章节
              section.sub_sections.forEach((subSection, subIndex) => {
                  formData.append(`sections[${sectionIndex}][sub_sections][${subIndex}][sub_section_title]`, subSection.sub_section_title);
                  // 存在上传文件则追加文件字段
                  if(subSection.file) {
                      formData.append(`sections[${sectionIndex}][sub_sections][${subIndex}][file]`, subSection.file);
                  }
              })
          })

          showLoader(true);
          axios.post('/api', formData, { headers: {'Content-Type': 'multipart/form-data'}}).then(response => {
              NotificationService.success(response.data.message);
              // 提交成功重置表单
              sections.splice(0, sections.length);
              sections.push({'section_title': '', 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]});
              course.title = '';
              course.description = '';
          }).catch(err => {
              NotificationService.error(err.response.data?.message || '提交失败');
          }).finally(() => {
              showLoader(false);
          });
      }

      return {
          course,
          createCourse,
          sections,
          addSection,
          addSubSection,
          uploadFile
      }
  }
}

后端适配

后端Laravel可以直接通过$request->input('sections')获取完整的章节数组,上传的子章节文件可以通过$request->file("sections.$sectionIndex.sub_sections.$subIndex.file")正常读取。


内容的提问来源于stack exchange,提问作者etranz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:57:00