VUE js call a child component method in a different component hierarchy

你。 提交于 2021-01-28 11:32:12

问题


I have this following vuejs component hierarchy. What i want to do it to invoke COMP_B_ONE validate() method, when COMP_A_TWO submit() method is invoked EVERY TIME.

MAIN_COMPONENT
              COMP_A_ONE
                    COMP_B_ONE
                          validate()
                    COMP_B_TWO
                          validate()
              COMP_A_TWO
                    submit()      

I've already implemented an emit when submit is triggered in COMP_A_TWO which can be listened in MAIN_COMPONENT

submit() {
  this.$emit('submit')
}

what seems to be the best approach in this regard? any suggestions appreciated.


回答1:


I can get this done by two ways.

1 - Global EventBus I will create an eventBus and register events on it from any file and listen it anywhere -

import { EventBus } from '@/eventBus' 
// simply import it to component which need listen the event


//Register Event where you have your methods - like In your COMP_B_TWO                   
 EventBus.$on('validate', () => { this.validate() })

// Emit event from another component
EventBus.$emit('validate')// Like directly from your COMP_A_TWO

To know how to create a eventBus follow this - Global Event Bus Vue


Another way I can think is

2 - Refs

Add reference to COMP_A_ONE like

<COMP_A_ONE ref = "one" />

Then add reference to COMP_B_ONE

<COMP_B_ONE ref = "b-one" />

Now when you trigger submit from main component

execute it -

this.$on('submit', () => {
  this.$refs.one['b-one'].validate()
})

It totally depends which way you wanna go -

  • If you need to call validate for many more places, I would suggest choosing EventBus
  • You just need current component to have it, use Refs


来源:https://stackoverflow.com/questions/56336049/vue-js-call-a-child-component-method-in-a-different-component-hierarchy

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