1

I'm trying to access to a method of an child component, to validate multiple forms.

I have an array named "forms", each form object has a randomly generated id. Based on these form objects I generate components and give them a ref name

In my validateAll method I'm trying to loop over all forms, find components with their id as component's ref name. When I find the component (no problem so far), I try to call the child's method. But I get an error.

This is where I render components with v-for loop:

<SupportRequestForm v-for="(form, idx) in forms" :key="form.id"
    ...
    :ref="`formRef${form.id}`"
/>

This is validateAll method, where I try to access child method:

validateAllForms() {
    return this.forms.find(form => {
        const formComponent = this.$refs[`formRef${form.id}`]
        console.log(formComponent)
        return formComponent.validateForm()
    })
}

And this is the error: error

I can access child component's method when it's a static ref name but I can't do the same thing when the is generated on the spot. Is this an expected behaviour or am I doing something wrong ?

Thank you very much in advance.

3
  • 1
    The function validate forms does not exist. The function you provided is called validateAllForms. Is this a typo? Commented Aug 23, 2021 at 11:49
  • No it's not, validateForm is the method of the child component (SupportRequestForm), which I'm trying to call. Commented Aug 23, 2021 at 11:50
  • 1
    why are you using find the method? Commented Aug 23, 2021 at 11:52

1 Answer 1

1

No need to bind each form to the form id, just create one ref called forms and since it's used with v-for it will contain the forms array :

When ref is used together with v-for, the ref you get will be an array containing the child components mirroring the data source

<SupportRequestForm v-for="(form, idx) in forms" :key="form.id" ref="forms" />

in method :

validateAllForms() {
     this.$refs.forms.forEach(formComponent=> {
       formComponent.validateForm()
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.