Home > Web Front-end > JS Tutorial > How to Update Parent Data from a Child Component in Vue.js 2.0?

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

Linda Hamilton
Release: 2024-10-29 19:24:02
Original
829 people have browsed it

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:

  1. Create a Child Component:
Vue.component('child', {
  template: '#child',
  props: ['value'],
  methods: {
    updateValue: function (value) {
      this.$emit('input', value);
    }
  }
});
Copy after login
  • The value prop is the data that the child component will display and modify.
  • The updateValue method is called when the input value in the child component changes. It emits an input event, passing the new value as an argument.
  1. Create a Parent Vue Instance:
new Vue({
  el: '#app',
  data: {
    parentValue: 'hello'
  }
});
Copy after login
  • The parentValue data property will hold the value that will be displayed in the parent template.
  1. Use v-model in the Child Component:
<child v-model="parentValue"></child>
Copy after login
  • Using v-model establishes a two-way binding between the parentValue data property and the prop value in the child component.
  1. Handle the Input Event in the Parent:

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

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!

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