I'm using the vue-cli scaffold for webpack
My Vue component structure/heirarchy currently looks like the following:
- App
- PDF Template
- Background
- Dynamic Template Image
- Static Template Image
- Markdown
- PDF Template
At the app level, I want a vuejs component method that can aggregate all of the child component's data into a single JSON object that can be sent off to the server.
Is there a way to access child component's data? Specifically, multiple layers deep?
If not, what is the best practice for passing down oberservable data/parameters, so that when it's modified by child components I have access to the new values? I'm trying to avoid hard dependencies between components, so as of right now, the only thing passed using component attributes are initialization values.
UPDATE:
Solid answers. Resources I found helpful after reviewing both answers:
The flow of props is one way down, a child should never modify its props directly.
For a complex application, vuex is the solution, but for a simple case vuex is an overkill. Just like what @Belmin said, you can even use a plain JavaScript object for that, thanks to the reactivity system.
Another solution is using events. Vue has already implemented the EventEmitter interface, a child can use
this.$emit('eventName', data)
to communicate with its parent.The parent will listen on the event like this: (
@update
is the shorthand ofv-on:update
)and update the data in the event handler:
Here is a simple example of custom events in Vue:
http://codepen.io/CodinCat/pen/ZBELjm?editors=1010
This is just parent-child communication, if a component needs to talk to its siblings, then you will need a global event bus, in Vue.js, you can just use an empty Vue instance:
For this kind of structure It's good to have some kind of Store.
VueJS provide solution for that, and It's called Vuex.If you are not ready to go with Vuex, you can create your own simple store.
Let's try with this
MarkdownStore.js
And now you can use those data everywhere, with importing this Store file
HomeView.vue
So that's the basic flow that you could use, If you dont' want to go with Vuex.
I am not sure this is a good practice or not.
In my child component, there are no buttons to emit changed data. its a form with somewhat 5~10 inputs. the data will be submitted once you click the process button in another component. so, I can't emit every property when it's changing.
So, what I did,
In my parent component, I can access child's data from "ref"
e.g
Note: If you do this all over the application i suggest move to vuex instead.