vue.jsvalidationvuejs2vue-componentelement-ui

how to validate child form from parent component in Vue


I have a child component which includes form:

<el-form :model="abc" ref="ruleForm" :rules="rules">
      <el-form-item prop="files">
        <abc-card :title="getTranslation('abc.files')">
          <file-selector v-model="abc.files" />
        </abc-card>
      </el-form-item>
</el-form>

And I want to add simple validations to this form:

rules: function () {
      return {
        files: [
          {
            type: 'object',
            required: true,
            trigger: 'change',
            message: 'Field required',
          },
        ],
      };
    },

But my click button is in the parent component:

<files v-model="editableAbc" ref="editableTab" />
<el-button type="primary" @click="submitForm()">Create</el-button>

methods: {
submitForm() {
        this.$refs.form.validate((isValid) => {
    if (!isValid) {
      return;
    }
    ////API CALLS////
  });
      },
    }

So I am trying to achieve that when the button is clicked the navigation should be rendered. How can I do that?


Solution

  • As per your requirement, My suggestion would be to use a ref on child component to access its methods and then on submit click in parent component, trigger the child component method.

    In parent component template :

    <parent-component>                                                                                                                                                        
          <child-component ref="childComponentRef" />
          <button @click="submitFromParent">Submit</button>                                                                      
    </parent-component>
    

    In parent component script :

    methods: {
      submitFromParent() {
        this.$refs.childComponentRef.submitForm();
      }
    }
    

    In child component script :

    methods: {
      submitForm() {
        // Perform validations and do make API calls based on validation passed.
        // If you want to pass success or failure in parent then you can do that by using $emit from here.
      }
    }