1
votes

I would like to know the best practice for implementing shared states between components in Vuejs.

Imagine situation A: you have a web app that shows a modal. The modal has the boolean state show. This state should change if the modal OK-button is clicked, but also if any part of the background is clicked, and perhaps even on some server pushed state change. Thus the modal should be able to change the state as should the parent app.

Situation B: you have a web app that shows input fields inside different components that share a common data value. If the user changes value through the field in one component, it should also update in the other. Again both should even update on a server push event.

Questions:

  • I am right that the correct way to go about this would be to use vuex and make the shared state a store field that is observed by and changed through emitted actions by all components / parents that need to modify that value?

  • Does that not introduce this kind of dangerous (since hard to handle) magic reactivity that we know from Meteor?

  • How to best document the flow, what depends on what?

1
Not sure whether this is the correct, "the vuey way" regarding A: I'd bind/unbind a click handler to document or maybe only $parent in the mount/unmount callbacks and close the modal from within the component (don't make the rest of the application handle modal close for clicks outside).try-catch-finally
Yes but I guess one of the key questions is how to close it. I followed the suggestions in the accepted answer.B M

1 Answers

4
votes

A: For a modal component, I'd say that show should be a prop. So the parent component can control the modal whatever it wants. In this case there is no shared state at all.

The modal itself doesn't need to know anything about the server. If the prop show is true, just display the modal and vice versa.

I think the mask layer is a part of the modal, so when the mask is clicked, the modal emits an event. The parent component receives the event and can decide to hide the modal or not to.

Vue has an official modal example here (thanks @craig_h for mentioning): https://vuejs.org/v2/examples/modal.html


B: Just bind the vuex state to the inputs. Nothing wrong.


Note that not all the components need to access the vuex store directly. For some pure UI components, just use props. So the parent components have the right to control them and increase flexibility.

I recommend you to read these docs:

Yes these are React / Redux docs. Since Vue is relatively young, react community has more documentation / articles. But both Vue and React are component-based libraries. The idea of how you design a component is basically the same.

You can also take a look at this vuex example: https://github.com/vuejs/vuex/tree/dev/examples/chat

This is a very simple example but it does use all the things I mentioned above. Emitting an event, some pure UI components...