Vue

使用Promise完成多组件表单的验证

芸殇
2023-07-03 / 0 评论 / 217 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年10月30日,已超过1097天没有更新,若内容或图片失效,请留言反馈。

  近期在项目中遇到一个表单需求,因为表单过多而且部分表单和其他表单可以通用,所以将表单拆成多个vue文件,但是又遇到表单验证的问题,最后用promise来完成多组件表单验证的需求。
  项目使用的是 ant-design-vue 这个UI库,他的验证表单组件使用 this.$refs.ruleForm.validate() 函数来完成表单的验证,我们可以在组件内在这个函数外面套一层 promise 函数。

methods: {
  validate() {
    return new Promise((resolve, reject) => {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          resolve('true')
        }else {
          reject(valid)
        }
      }
    })
  }
}

   在父组件中,我们使用 Promise.all 和 ref 来完成多组件的同时验证。

<template>
  <div>
    <child-one ref="childOne"></child-one>
    <child-two ref="childTwo"></child-two>
    <a-button icon="check" type="primary" @click="submit">提 交</a-button>
  </div>
</template>

<script>
import ChildOne from './ChildOne'
import childTwo from './childTwo'
export default {
  components: { ChildOne, childTwo },
  methods: {
    submit() {
      const refArray = ['childOne', 'childTwo']
      Promise.all(refArray.map(item => this.$refs[item].validate())).then(() => {
        // 提交的交互写在这里,只有在所有的组件中的表单验证通过后,才会执行这里面的请求交互
      })
    }
  }
}
</script>
0

评论 (0)

取消