Communicating Parent-Child Data Updates in Vue.js
As you delve into the world of Vue.js, you'll encounter situations where you need to update data from a child component to its parent. While two-way binding was prevalent in Vue 1.x, it has been deprecated in favor of an event-driven approach in Vue 2.x.
To handle data updates between parent and child in Vue 2.0, you can leverage custom components with v-model. V-model is a special syntax that provides a convenient shortcut for the event-driven architecture Vue adopts.
Consider the following example:
<code class="js">Vue.component('child', { template: '#child', props: ['value'], methods: { updateValue: function (value) { this.$emit('input', value); } } }); new Vue({ el: '#app', data: { parentValue: 'hello' } });</code>
<code class="html"><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script> <div id="app"> <p>Parent value: {{parentValue}}</p> <child v-model="parentValue"></child> </div> <template id="child"> <input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)"> </template></code>
In this example:
Using this event-based approach, you can effectively manage parent-child data updates while maintaining a decoupled and modular component architecture.
The above is the detailed content of How Can I Communicate Data Updates Between Parent and Child Components in Vue.js?. For more information, please follow other related articles on the PHP Chinese website!