Home > Article > Web Front-end > How to Update Parent Data from a Child Component in Vue.js 2.0?
Update Parent Data from Child Component in Vue.js
In Vue.js 2.0, traditional two-way binding has been replaced by an event-driven architecture. This means that a child component should not directly modify its props. Instead, it should emit events and allow the parent to respond to those events.
To update the parent data from a child component, you can use a custom component with v-model. This special syntax provides a shorthand for the event-driven approach, allowing you to bind a prop directly to a value in the child component. Here's how it works:
Vue.component('child', { template: '#child', props: ['value'], methods: { updateValue: function (value) { this.$emit('input', value); } } });
new Vue({ el: '#app', data: { parentValue: 'hello' } });
<child v-model="parentValue"></child>
When the input value changes in the child component, the updateValue method will emit an input event. In the parent Vue instance, you can handle this event using the following code:
handleInputEvent(value) { this.parentValue = value; }
This will update the parentValue data property whenever the input value in the child component changes.
By following this event-driven approach, you can effectively update parent data from a child component in Vue.js 2.0 and maintain a clean and modular architecture.
The above is the detailed content of How to Update Parent Data from a Child Component in Vue.js 2.0?. For more information, please follow other related articles on the PHP Chinese website!