针对el-form的数据源是对象嵌套对象,在进行数据绑定和校验时和单层的对象有一点区别,
具体是下面两部分:
数据源:
js
fromData: {
name: '',
health: {
height: ''
}
}
1、 给 el-form-item
的 prop
设为:prop="health.height"
。
v-model
设为:v-model="fromData.health.height"
c
<el-form-item label="身高" prop="health.height">
<el-input v-model="fromData.health.height" clearable />
</el-form-item>
2、校验规则rules
对象对应的key设置为数据源内部的值: 'health.height'
c
rules: {
'health.height': [{ required: true, message: '请输入身高', trigger: 'blur' }]
}
具体代码
html
<template>
<div>
<el-form ref="fromRef" :model="fromData" :rules="rules">
<el-form-item label="姓名" prop="name">
<el-input v-model="fromData.name" clearable />
</el-form-item>
<el-form-item label="身高" prop="health.height">
<el-input v-model="fromData.health.height" clearable />
</el-form-item>
</el-form>
<el-button @click="onSubmit()">提交</el-button>
</div>
</template>
<script>
export default {
data() {
return {
fromData: {
name: '',
health: {
height: ''
}
},
rules: {
name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
'health.height': [{ required: true, message: '请输入身高', trigger: 'blur' }]
}
}
},
methods: {
onSubmit() {
this.$refs['fromRef'].validate((valid) => {
if (valid) {
console.log('校验通过')
console.log('fromData', JSON.stringify(this.fromData))
}
})
}
}
}
</script>
<style scoped></style>