[Vuejs]-VueJS: Change data within child component and update parent's data.

2👍

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://v2.vuejs.org/v2/guide/components.html#Emitting-a-Value-With-an-Event

👤Imre_G

1👍

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

0👍

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.

👤Ealhad

Leave a comment