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

How to Update Parent Data from a Child Component in Vue.js?

Susan Sarandon
Release: 2024-10-28 07:15:02
Original
115 people have browsed it

How to Update Parent Data from a Child Component in Vue.js?

Updating Parent Data from Child Component in Vue.js

In Vue.js, two-way binding allows child components to directly mutate the properties of their parent components. However, with the release of Vue 2.0, two-way binding has been deprecated in favor of an event-driven architecture.

Solution: Event-Driven Communication

In this approach, the child component raises events with the updated value. The parent component, in turn, handles these events and modifies its data accordingly. For example, let's create a custom child component with a text input:

<code class="javascript">Vue.component('child', {
  template: '#child',
  props: ['value'],
  methods: {
    updateValue(value) {
      this.$emit('input', value);
    }
  }
});</code>
Copy after login

Updating the Parent Value

In the child component, the updateValue method is called whenever the input value changes. This method emits an 'input' event, passing the updated value as the argument.

Listening for Events in the Parent

In the parent Vue instance:

<code class="javascript">new Vue({
  el: '#app',
  data: {
    parentValue: 'hello'
  },
  methods: {
    handleInput(value) {
      this.parentValue = value;
    }
  }
});</code>
Copy after login

Binding with v-model

Vue.js provides a convenient shorthand for two-way binding called v-model. Using v-model on a form element automatically binds it to the specified property in the parent component. The code below demonstrates this:

<code class="html"><child v-model="parentValue"></child></code>
Copy after login

In this example, the child component's value property is bound to the parentValue property in the parent component. Changes to the input in the child component will automatically update the parentValue in the parent component.

The above is the detailed content of How to Update Parent Data from a Child Component 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
Latest Articles by Author
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!