Home >Web Front-end >JS Tutorial >How to Update Parent Data from Child Components in Vue.js Using v-model?

How to Update Parent Data from Child Components in Vue.js Using v-model?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 21:04:30725browse

How to Update Parent Data from Child Components in Vue.js Using v-model?

Updating Parent Data from Child Components in Vue.js

In Vue.js, it's important to handle data flow between parent and child components effectively. This article discusses a scenario where you want to update the parent's data from an input field within a child component.

Problem:

In Vue.js 2.0 and above, two-way binding has been deprecated. When using props to pass data from the parent to the child, direct prop mutation is discouraged as it can lead to console warnings.

Solution:

To update the parent's data, you can use the event-driven architecture and custom components with v-model. V-model provides a syntax for two-way binding that uses events to communicate between the parent and child.

Implementation:

Create a child component with a template that includes the input field:

<code class="html"><template id="child">
  <input type="text" v-bind:value="value" v-on:input="updateValue($event.target.value)">
</template></code>

In the child component's script, add a 'value' prop and a 'updateValue' method that emits an 'input' event with the updated value:

<code class="javascript">Vue.component('child', {
  template: '#child',

  props: ['value'],

  methods: {
    updateValue: function (value) {
      this.$emit('input', value);
    }
  }
});</code>

In the parent view, create a Vue instance with the parent data and use the child component with v-model:

<code class="html"><div id="app">
  <p>Parent value: {{ parentValue }}</p>
  <child v-model="parentValue"></child>
</div></code>

When the input field value in the child component changes, the 'updateValue' method is called and the updated value is emitted as an 'input' event. The parent Vue instance receives the emitted event and updates its 'parentValue' accordingly.

The above is the detailed content of How to Update Parent Data from Child Components in Vue.js Using v-model?. 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