在 el-form 中嵌套 el-table 树形结构时,如果需要对多个 children 表单进行必填校验,可以通过以下步骤实现:

  1. 在 el-table 中的 columns 中添加需要校验的 children 表单的字段,并设置其对应的 prop 和 label。
  2. 在 el-form 中使用 ref 属性绑定表单实例,可以在代码中通过 this.$refs.form 来访问表单实例。
  3. 在 el-form 中添加 submit 方法,该方法中可以通过 this.$refs.form.validate() 来触发表单校验。
  4. 在表单校验之前,需要对所有 children 表单的必填项进行手动设置 required 属性为 true,并且在对应的 label 后添加 * 号,表示该项为必填项。
  5. 在 submit 方法中,判断是否所有的 children 表单都通过了校验,如果有任何一个未通过,则提示用户进行修正。

代码示例:

<template>
  <el-form ref="form" :model="formData" label-width="120px" @submit.native.prevent>
    <el-table :data="tableData" :tree-props="{children: 'children'}" style="width: 100%">
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="age" label="年龄"></el-table-column>
      <el-table-column prop="gender" label="性别"></el-table-column>
      <el-table-column label="子节点">
        <template slot-scope="scope">
          <el-table :data="scope.row.children" :tree-props="{children: 'children'}" style="width: 100%">
            <el-table-column prop="name" label="名称" :required="true">*</el-table-column>
            <el-table-column prop="age" label="年龄" :required="true">*</el-table-column>
            <el-table-column prop="gender" label="性别" :required="true">*</el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="submitForm">提交</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      formData: {},
      tableData: []
    };
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 所有表单项都通过校验
          console.log('submit form');
        } else {
          // 子表单未通过校验
          this.$message.error('请修正表单错误');
        }
      });
    }
  }
};
</script>
Element UI 中 el-form 嵌套 el-table 树形结构表单必填校验

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

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