Is the solution for passing data up the chain in Vue.js really to chain event listeners/emitters?

爱⌒轻易说出口 提交于 2019-12-20 06:07:14

问题


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.

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?


回答1:


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:



来源:https://stackoverflow.com/questions/40922770/is-the-solution-for-passing-data-up-the-chain-in-vue-js-really-to-chain-event-li

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