Home  >  Article  >  Web Front-end  >  How Can I Communicate Data Updates Between Parent and Child Components in Vue.js?

How Can I Communicate Data Updates Between Parent and Child Components in Vue.js?

DDD
DDDOriginal
2024-10-27 16:15:01239browse

How Can I Communicate Data Updates Between Parent and Child Components in Vue.js?

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:

  • The child component has a prop named value that is synchronized with the data property in the parent through v-model.
  • When the user types in the input field of the child component, the updateValue method is triggered.
  • The updateValue method emits an input event to the parent component with the updated value.
  • The parent component receives the input event and updates its own parentValue data property accordingly.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn