Vue - Element el-form 表单对象多层嵌套校验

针对el-form的数据源是对象嵌套对象,在进行数据绑定和校验时和单层的对象有一点区别,
具体是下面两部分:

数据源:

fromData: {
  name: '',
  health: {
    height: ''
  }
}

1、 给 el-form-itemprop设为:prop="health.height"
v-model 设为: v-model="fromData.health.height"

  <el-form-item label="身高" prop="health.height">
    <el-input v-model="fromData.health.height" clearable />
  </el-form-item>

2、校验规则rules对象对应的key设置为数据源内部的值: 'health.height'

rules: {
	'health.height': [{ required: true, message: '请输入身高', trigger: 'blur' }]
}

具体代码

<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>

你可能感兴趣的:(Vue,vue.js,javascript,前端)