Vue parent component calls Form form validation of child components

Requirement 1: The parent component calls the form validation method of the child component. If the validation is successful, continue to the next operation. If the validation fails, prompt the user and return.

insert image description here

Requirement 2: The parent component verifies the form verification methods of multiple child components. If the verification is successful, continue to the next operation. If the verification fails, prompt the user and return.

insert image description here

Requirement 1, the code is as follows:

1. Introduce the child component in the parent component

 <el-dialog
  :title="title"
   :visible.sync="dialogVisible"
   width="50%"
   :before-close="handleClose"
 >
   <exciter-edit ref="alternatorRef" />
   <span slot="footer" class="dialog-footer">
     <el-button @click="handleClose">取 消</el-button>
     <el-button type="primary" @click="transformerConfirm(insEdit)"
       >确 定</el-button
     >
   </span>
 </el-dialog>

2. Validation methods in subcomponents

方法一:
 async justify() {
    
    
 //校验成功则方法自动返回true,校验方法报错则说明校验失败,返回false
	try {
    
    
	   return await this.$refs['ruleFormRef'].validate()
	 } catch (error) {
    
    
	   return false
	 }
	}

Method Two:

validate(callback){
    
    
 //这个form是子组件内部 el-form 的 ref="contentForm"
   this.$refs.contentForm.validate((valid) => {
    
    
     callback(valid)
   })
 }

3. Click the [OK] button in the parent component to call the method
Method 1: Call the verification method of the child component to judge:

async transformerConfirm(value) {
    
    
  //调用校验子组件的方法
    let flag = await this.$refs.alternatorRef.justify()
    //如果子组件校验方法返回ture,则接着进行其他操作,返回false则提示用户
    if (flag) {
    
    
		//to do something
    } else {
    
    
      this.$message.warning('校验失败')
    }
  }

Method 2: Verify by calling the subcomponent form method:

async transformerConfirm(value) {
    
    
  //调用校验子组件的方法
   this.$refs['contentForm'].validate((valid) => {
    
    
        if (valid) {
    
    ...}
      }
}

Requirement 2, the code is as follows:

1. If the parent component checks multiple child components

saveData(flag){
    
    
  const a1 = new Promise((resolve, reject) => {
    
    
      this.$refs.contentForm.validate((valid) => {
    
    
        if (valid) resolve()
      })
    })
    const a2 = new Promise((resolve, reject) => {
    
    
      this.$refs.pageForm.validate((valid) => {
    
    
        if (valid) resolve()
      })
    })
    Promise.all([a1, a2]).then(() => {
    
    
    //全部验证通过
    //写保存方法
    })
  },

Guess you like

Origin blog.csdn.net/qq_44552416/article/details/131592414