Access to a function\$refs in another component not in the same level as current one

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-10 15:49:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!