表单中存在数组字段的时候,如何做格式校验?

167 阅读1分钟

前段时间遇到需求:

  • 表单需要与后端交互的字段是个数组
  • 可以增加删除数组项
  • 需要校验每一项的填写格式

需求大致效果如下图

image.png

经过一番百度,且经过自己的实践,特此记录一下,直接上代码

// 核心代码
<el-form-item label="IP">
    <el-table
      :data="form.ipList"
      :show-header="false"
      border
      style="width: 100%"
    >
      <el-table-column prop="ip">
        <template slot-scope="scope">
          <el-form-item
            :prop="'ipList.' + scope.$index + '.ip'"
            :rules="rules.ip"
            label-width="0"
          >
            <el-input
              v-model="scope.row.ip"
              placeholder="请输入IP地址"
            ></el-input>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
  </el-form-item>

其中 ipList 的格式如下:

const form = reactive({
    ipList: [{
        ip: ''
    }]
})

校验规则在rules对象中正常写就 OK 了!