本文主要讲element-ui的el-form表单和el-table校验嵌套使用校验el-input和el-select
点击保存可校验el-input和el-select是否有值,不符合校验规则就标红提醒
<el-form :model="formData" :rules="formData.rules" ref="formRef">
<el-table
:data="formData.tableData"
style="width: 100%">
<el-table-column
prop="id"
label="单号"
width="100">
el-table-column>
el-table>
el-form>
<el-table-column
prop="name"
label="商品名"
width="180">
<template slot-scope="scope">
<el-form-item>
<el-input v-model="scope.row.name">el-input>
el-form-item>
template>
el-table-column>
对象里放el-table用到的数组和rules
formData: {
rules: {
name: {
required: true,
message: '请输入商品名',
tirgger: ['blur', 'change']
},
selected: {
required: true,
message: '请选择',
tirgger: 'change'
}
},
tableData: [
{id: '001'},
{id: '002'},
{id: '003'},
]
},
1.el-form绑定: rules使用formData.rules整个对象,同时定义一个ref
<el-form :model="formData" :rules="formData.rules" ref="formRef">
2.保证prop必须唯一
自定义prop:使用 列表数据属性名+列的下标scope.$index+列的数据属性名
<el-table-column
prop="name"
label="商品名"
width="180">
<template slot-scope="scope">
<el-form-item :prop="'tableData.' + scope.$index + '.name'" :rules="formData.rules.name">
<el-input v-model="scope.row.name">el-input>
el-form-item>
template>
el-table-column>
注意:如果不是使用列表数据属性名tableData,会出现报错
Error: please transfer a valid prop path to form item
3.保证每一个el-form-item都要配置rules属性
rules使用formData.rules对应的属性的规则
<template>
<div>
<el-form :model="formData" :rules="formData.rules" ref="formRef">
<el-table
:data="formData.tableData"
style="width: 100%">
<el-table-column
prop="id"
label="单号"
width="100">
el-table-column>
<el-table-column
prop="name"
label="商品名"
width="180">
<template slot-scope="scope">
<el-form-item :prop="'tableData.' + scope.$index + '.name'" :rules="formData.rules.name">
<el-input v-model="scope.row.name">el-input>
el-form-item>
template>
el-table-column>
<el-table-column
prop="class"
label="分类">
<template slot-scope="scope">
<el-form-item :prop="'tableData.' +scope.$index + '.class'" :rules="formData.rules.selected">
<el-select v-model="scope.row.class">
<el-option
v-for="item in classOption"
:key="item.value"
:label="item.label"
:value="item.value"
>el-option>
el-select>
el-form-item>
template>
el-table-column>
el-table>
el-form>
<el-button @click="submitForm('formRef')">提交el-button>
div>
template>
<script>
export default {
data() {
return {
formData: {
rules: {
name: {
required: true,
message: '请输入商品名',
tirgger: ['blur', 'change']
},
selected: {
required: true,
message: '请选择',
tirgger: 'change'
}
},
tableData: [
{id: '001'},
{id: '002'},
{id: '003'},
]
},
classOption: [
{
value: 0,
label: '分类1'
},
{
value: 0,
label: '分类1'
}
]
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
}
}
script>