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

How to Update Parent Data with Event-Driven Architecture in Vue.js?

Barbara Streisand
Release: 2024-10-27 11:46:01
Original
358 people have browsed it

How to Update Parent Data with Event-Driven Architecture in Vue.js?

Updating Parent Data with Event-Driven Architecture in Vue.js

In Vue.js, two-way binding is no longer available in version 2.0 due to its deprecation. Instead, a more event-driven architecture is employed, where children components should not directly manipulate their props. Rather, they should use event emitting to communicate with their parent components.

If you are looking to update the parent data from a child component, consider using a custom component with v-model. This special syntax provides a close approximation to two-way binding, but is implemented using events.

Here's a simple example:

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

  // The child has a prop named 'value'. v-model will automatically bind to this prop.
  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 v-model directive bound to the parentValue data property of the parent component.
  • When the user enters a value into the input field in the child component, the updateValue method is triggered.
  • This method emits an input event with the value as a parameter, which is handled by the parent component.
  • The parent component updates its parentValue data property based on the value emitted by the child component.

The above is the detailed content of How to Update Parent Data with Event-Driven Architecture 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!