VUE js调用不同组件层次结构中的子组件方法

问题描述:

我有以下 vuejs 组件层次结构.当 COMP_A_TWO submit() 方法每次被调用时,我想要做什么来调用 COMP_B_ONE validate() 方法.

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()      

我已经在 COMP_A_TWO 中触发提交时实现了一个发射,可以在 MAIN_COMPONENT 中收听

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.

我可以通过两种方式完成这项工作.

I can get this done by two ways.

1 - 全局 EventBus我将创建一个 eventBus 并从任何文件在其上注册事件并在任何地方收听 -

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

要了解如何创建 eventBus,请按照此 - 全局事件总线 Vue

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

我能想到的另一种方式是

Another way I can think is

2 - 参考

<COMP_A_ONE ref = "one" />

然后添加对COMP_B_ONE

<COMP_B_ONE ref = "b-one" />

现在当你从main component

执行它 -

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

这完全取决于你想走哪条路 -

It totally depends which way you wanna go -

  • 如果你需要在更多地方调用validate,我建议你选择EventBus
  • 你只需要当前的组件来拥有它,使用Refs
  • 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