问题
I've a Vue 2 application, with different components nested. Their structure is kinda (I'm skipping the not-relevant ones for my question):
<root>
<app>
<component1/>
...
<component3>
<billingAddress>
<customForm/>
</billingAddress>
<shippingAddress>
<customForm/>
</shippingAddress>
</component3>
...
<lastComponent/>
</app>
</root>
The customForm1 and 2 contain a form, validated via vee-validate - so there' a ValidationObserver component.
Those two forms are validated at the relative submit - the submit action is custom, when they are successfully validated, they are hidden - and there is no redirect.
On the "lastComponent" there's a "submit" button whichis disabled until both form are correctly submitted and which does some other logic.
Today I've been asked to change the behaviour of that button: now it may launch the validation and the submit of those two form, skipping so the "manual" submission of the users.
I'm not sure how can handle this, as the ValidationObserver and the custom actions are in components unrelated to the "lastComponent".
For now, I've managed traversing the tree of $refs starting from $root, but I don't really like an approach so fragile.
This is what I'm doing in my "submit" action:
let shippingAddressValid = await this.$root.$children[0].$refs.addresses.$refs.shippingAddress.$refs.addressForm.$refs.shippingAddressForm.validate();
if (shippingAddressValid) {
await this.$root.$children[0].$refs.addresses.$refs.shippingAddress.$refs.addressForm.updateAddress();
}
I'd like to know if there's a better approach.
I've found this anweser that is interesting. However, I haven't found a way to set up a custom event via "global bus" that returns me a value, asynchronously. I mean, it's mandatory, to get the "valid" state of the form, before calling the submit method. I can't just call the validation in the method, because I have to do some logic if the form is invalid.
来源:https://stackoverflow.com/questions/64666338/access-to-a-function-refs-in-another-component-not-in-the-same-level-as-current