例如:
<el-form ref="form" :model="postData" :rules="rules" class="common-form" label-width="118px" size="mini">
<el-row>
<el-col :span="12">
<el-form-item prop="custType" label="客户属性">
<el-radio-group v-model="postData.custType" @change="changeCustomerType">
<el-radio label="直属客户">直属客户</el-radio>
<el-radio label="代理商">代理商</el-radio>
</el-radio-group>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="客户名称" class="hintparent" prop="custId">
<el-select
v-model="postData.custId"
placeholder="请选择"
>
<el-option
v-for="item in customers"
:key="item.id"
:label="item.cname"
:value="item.id"
></el-option>
</el-select>
</el-form-item>
</el-col>
<el-row>
</el-form>
数据结构为:
postData: {
custType: '',
custId: '',
},
校验规则为
rules: {
custType: [{ required: true, message: '请选择客户属性', trigger: 'change' }],
custId: [{ required: true, message: '请选择客户名称', trigger: 'change' }]
}
注意到 prop里的名称和属性名和rules里的检验字段名需保持一致。
现有一段数据结构如下:
postData: {
stamp: {
person: null,
tel: null,
reason: null
}
}
<el-form-item
prop="stamp.concatPerson"
label="联系人"
:rules="{ required: postData.stamp.needPost === 0, message: '请填写联系人', trigger: 'change' }"
>
<el-input v-model="postData.stamp.concatPerson"></el-input>
</el-form-item>
<el-form-item
v-if="postData.stamp.needPost === 0"
prop="stamp.tel"
label="联系电话"
class="hintparent"
:rules="[
{ required: postData.stamp.needPost === 0, message: '请填写联系电话', trigger: 'change' },
{
pattern: /^[\d\-]+$/,
message: '电话格式不正确',
trigger: 'change'
},
{ max: 20, message: '电话格式不正确', trigger: 'change' }
]"
>
<el-input v-model="postData.stamp.tel"></el-input>
</el-form-item>
<el-form-item prop="stamp.reason" label="盖章原因" class="hintparent">
<el-input
v-model="postData.stamp.reason"
maxlength="2000"
show-word-limit
type="textarea"
:autosize="{ minRows: 4 }"
:rules="[
{ required: true, message: '请填写盖章原因', trigger: 'change' },
{ max: 2000, message: '最多只能输入2000个字', trigger: 'change' }
]"
></el-input>
</el-form-item>
此时props传的是去掉最外层之后的嵌套对象,rules写在组件内部,没有拎出来的原因是因为我需要判断required的值,而在data()里获取不到this会报错。
在不需要做我这种判断时,也可以拎出来,写法如下
//第一种方式
stamp: {
reason: [
{ required: true, message: '请填写盖章原因', trigger: 'change' },
{ max: 2000, message: '最多只能输入2000个字', trigger: 'change' }
]
}
//第二种方式
'stamp.reason': [
{ required: true, message: '请填写盖章原因', trigger: 'change' },
{ max: 2000, message: '最多只能输入2000个字', trigger: 'change' }
]
两种方式差不多,第二种比较简洁,第一种在嵌套对象比较多时可读性更高
开发中需要注意的是,需要初始化嵌套层级多的数据的n-1层,不然会报错哦,比如这里就需要初始化:postData.stamp: {},
如果是postData.stamp.my.reason,就需要初始化到postData.stamp.my: {}