在项目有遇到table中嵌套form,并且带有表单验证的需求,效果图如下:
刚开始el-form-item定义了静态prop(prop=“sn”),结果input填入值后错误提示一直存在,自定义校验的value也为undefined,然后经百度大神提点,得知出错在prop
- ⚠️应该写动态prop保证唯一性。
:prop="'monitorData.' + scope.$index + '.sn'"
- ⚠️不只是el-form才配置,每一个el-form-item都要配置rules属性
<el-form :model="monitorForm" :rules="monitorForm.monitorRules" ref="monitorForm">
<el-table
class="blue-theme add-virtual-table"
empty-text="请 新增填写行 进行填写"
:data="monitorForm.monitorData"
style="width: 100%;">
<el-table-column
type="index"
align="center"
width="50"/>
<el-table-column
prop="sn"
label="SN">
<template slot-scope="scope">
<el-form-item
:prop="'monitorData.' + scope.$index + '.sn'"
:rules="monitorForm.monitorRules.sn">
<el-input
class="light-blue-theme"
clearable v-model="scope.row.sn"
placeholder="请输入sn"/>
</el-form-item>
</template>
</el-table-column>
<el-table-column
label="品牌">
<template slot-scope="scope">
<el-form-item
:prop="'monitorData.' + scope.$index + '.type'"
:rules="monitorForm.monitorRules.type">
<el-input
class="light-blue-theme"
v-model="scope.row.type"
placeholder="请输入品牌名称"/>
</el-form-item>
</template>
</el-table-column>
<el-table-column
label="高度"
min-width="160">
<template slot-scope="scope">
<el-form-item
:prop="'monitorData.' + scope.$index + '.height'"
:rules="monitorForm.monitorRules.height">
<el-input
class="light-blue-theme"
v-model="scope.row.height"
placeholder="请输入高度"/>
</el-form-item>
</template>
</el-table-column>
<el-table-column
prop="date"
label="操作"
width="100">
<template slot-scope="scope">
<el-button
size="mini"
type="danger"
icon="el-icon-delete"
circle
@click="handleDeleteRow(scope.$index, scope.row)"></el-button>
</template>
</el-table-column>
</el-table>
</el-form>
data
monitorForm: {
monitorData: [],
monitorRules: {
sn: [
{ required: true, message: 'SN不能为空', trigger: 'blur' }
],
type: [
{ required: true, message: '品牌名称不能为空', trigger: 'blur' }
],
height: [
{ required: true, message: '高度不能为空', trigger: 'blur' }
]
}
}, // 存储表格table信息