Home  >  Article  >  Web Front-end  >  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
Linda HamiltonOriginal
2024-10-29 19:24:02737browse

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);
    }
  }
});
  • 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'
  }
});
  • 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>
  • 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;
}

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:
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