vue+elementui,使用form表单时,有时需要用到多表单一起验证,待都校验通过后再执行后续动作。

解决方法:先对每一个表单进行校验,返回一个promise对象,然后使用Promise.all方法对所有返回的promise对象判断,全部是fulfilled的时候执行后续逻辑。代码如下:

<template>
  <div>
    <el-form
      ref="form1"
      :model="form1" 
      :rules="rules1" 
    >
      <el-form-item label="标题" prop="title1">
        <el-input
          v-model="form1.title1"
          placeholder="请输入标题"
        />
      </el-form-item>
      <el-form-item label="内容" prop="content1">
        <el-input
          v-model="form1.content1" 
          type="textarea"
          resize="none"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="form2"
      :model="form2" 
      :rules="rules2" 
    >
      <el-form-item label="标题" prop="title2">
        <el-input
          v-model="form2.title2"
          placeholder="请输入标题"
        />
      </el-form-item>
      <el-form-item label="内容" prop="content2">
        <el-input
          v-model="form2.content2" 
          type="textarea"
          resize="none"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <el-button
      type="primary"
      @click="submitForm"
    >提交</el-button>
  </div>
</template>

<script>

export default {

  data() {
    return {
      form1: {},
      form2: {},
      // 表单校验
      rules1: {
        title1: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        content1: [
          { required: true, message: "请输入内容", trigger: "blur" }
        ]
      },
      rules2: {
        title2: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        content2: [
          { required: true, message: "请输入内容", trigger: "blur" }
        ]
      },
    }
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      let formValidates = [
        this.$refs["form1"].validate(),
        this.$refs["form2"].validate(),
      ]
      Promise.all(formValidates).then(() => {
        // TODO
        // 校验通过后的逻辑
      })
      
    }
  }
}
</script>

Logo

前往低代码交流专区

更多推荐