问题
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 choosingEventBus
- 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