1

The Vue API Docs/Guide talk about the pattern of parents passing props to children, who communicate back up to their parents via events. Additionally, the guide stresses that children absolutely should not mutate parent data, as that is the responsibility of the parent.

enter image description here

For a mostly-flat structure where you have one parent (e.g. 'App') and all components are children of that one parent, this works okay; any event only has to bubble once.

However, if you are composing a structure that is compartmentalized (e.g. App (holds state) -> ActiveComponent -> FormGroup -> Inputs...) then building interaction within the deeper parts (like the FormGroup/Inputs) requires making an event chain on each connection. Input will need to make an event v-on:keyup.enter="addInputValue"; then FormGroup will need to have a v-on:addInputValue="bubbleInputValue"; ActiveComponent will need a v-on:bubbleInputValue="bubbleInputValue"; and finally the App will need to respond to bubbleInputValue.

This seems really absurd that every link in the chain needs to know how to be responsible for handling the bubbling of an event that App wants to know about from the deepest branch of Input. The Vue guide suggests a State Store pattern to deal with this -- but that doesn't actually address the chaining (as you're simply adding a different root; the Store).

Is there an accepted convention/pattern for addressing the difficulty of communication that traverses a tall tree of components?

Mike Manfrin
  • 2,722
  • 2
  • 26
  • 41
  • It will keep bubbling up the chain until something handles it and returns false. You don't need to keep passing it. – Jeff Dec 02 '16 at 00:43
  • @Jeff - that's only true for Vue 1. In Vue 2, event can only be listened to by the immediate parent. – Joseph Silber Dec 02 '16 at 02:40
  • "Is there an accepted convention/pattern for addressing the difficulty of communication that traverses a tall tree of components?" Yes. Don't use the tree. Use [Vuex](http://vuex.vuejs.org/en/intro.html). – Joseph Silber Dec 02 '16 at 02:41

1 Answers1

4

If you really want to keep state at app level, you can use non parent child communication

Which will be like following:

var bus = new Vue()
----------------------------
// in component A's method
bus.$emit('id-selected', 1)
----------------------------
// in component B's created hook
bus.$on('id-selected', function (id) {
  // ...
})

But as stated in documentation:

In more complex cases, you should consider employing a dedicated state-management pattern.

Vuex to the rescue

As suggested in the comments, the general practice in the community for centralise state management is vuex, so all your state is separated from your component and view, you have actions which changes the store, which reactively changes your view. Flow look like this:

enter image description here

tony19
  • 125,647
  • 18
  • 229
  • 307
Saurabh
  • 71,488
  • 40
  • 181
  • 244