Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-27 16:15:01
Original
238 people have browsed it

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>
Copy after login
<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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!