Vuejs: Change Data Within Child Component And Update Parent's Data.
Solution 1:
You are looking for $emit. In the child component emit the data changes to the parent by using $emit('updateData', payload). You can then listen for the update on the component, for example like this:
<business-hours @updateData="doSomething(payload)":injected-data="hours":injected-days="data.days[0]">
You can use the doSomething method to update your main data with the changes from the component. This way they will be kept when the components are rerendered.
More info here: https://vuejs.org/v2/guide/components.html#Emitting-a-Value-With-an-Event
Solution 2:
Instead of changing the data into the child component first then update the parent component what you should do emit the event on the parent component about the change in child component and set the state in parent component then child component will re-render by that. In this way you maintain the philosophy of parent child component that parent should pass data into child and child notify parent of any change.
You can read more about it in this blog post - https://medium.com/@sky790312/about-vue-2-parent-to-child-props-af3b5bb59829
Solution 3:
Implement v-model
for your component.
From the Vue documentation:
For this to actually work though, the inside the component must:
- Bind the value attribute to a value prop
- On input, emit its own custom input event with the new value
In code, this translates as:
props: ['value']
in your component declaration, and calling
this.$emit('input', <something>)
to update the value.
Post a Comment for "Vuejs: Change Data Within Child Component And Update Parent's Data."