[Vuejs]-Vue common component communicate with different parent

0👍

Use this.$dispatch('eventName', data) (for Vue 2.x, use this.$emit('eventName', data)), to trigger an event to any parent, grandparent and further up the chain (you can use this.$broadcast('eventName', data) to trigger events down the chain in Vue < 2.x).

If the parent has an event called ‘eventName’ then it will fire this event.

If you have multiple parents, you can give them each a different event and from the child fire this specific event via dispatch. You can also give each parent the same event and pass a data prop that specifies what the parent should do. Third option is to refer to the specific parent:

var parent = new Vue({ el: '#parent' })
// access child component instance
parent.$refs.eventName()

Each option has pros and cons. The best solution depends on the context. But I think that the best solution in general is option 1. Then you don’t need an additional data parameter. Option 3 is not loosely coupled.

For more info: https://vuejs.org/guide/components.html

Leave a comment