Vue's bidirectional data binding presents a challenge when attempting to update the parent component from a child component

I have the following components:

Parent Component:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12" class="parent">
        <p>I am the Parent component</p>
        <button @click="changeDetail" :name.sync="name">Change Details</button>
        <Child v-bind:name="name"></Child>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Child from "./Child";
export default {
  name: "Parent",

  data: () => ({
    name: "test"
  }),
  methods: {
    changeDetail() {
      this.name = "Updated from Parent";
    }
  },
  components: {
    Child
  }
};
</script>

Child Component:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12">
        <p>My name is: {{ name}}</p>
        <button @click="resetName">Reset the name</button>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    }
  },
  data: () => ({
    newName: "Updated from Child"
  }),
  methods: {
    resetName() {
      this.$emit("update:name", this.newName);
    }
  }
};
</script>

In reference to https://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier, I attempted using update and sync to pass props from child to parent, but it did not work as expected. Can someone help me identify what might be missing or incorrect in my code?

Answer №1

To ensure easy external data access and modification, it is recommended to bind a computed property to the prop in your template instead of directly binding it. This approach will also streamline your code and eliminate the need for manual updates.

Parent:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12" class="parent">
        <p>I am the Parent component</p>
        <button @click="changeDetail">Change Details</button>
        <Child v-bind:name.sync="name"></Child>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Child from "./Child";
export default {
  name: "Parent",

  data() {
    return {
      name: "test"
    };
  },
  methods: {
    changeDetail() {
      this.name = "Updated from Parent";
    }
  },
  components: {
    Child
  }
};
</script>

Child:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12">
        <p>My name is: {{ currentName }}</p>
        <button @click="resetname">Reset the name</button>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  //   props: ["name"],
  props: {
    name: {
      type: String,
      required: true
    }
  },
  data() {
    // Be cautious with using fat arrow functions for data 
    // as *this* refers to the parent scope rather than the component itself.
    return {};
  },
  computed: {
    currentName: {
        get() { return this.name },
        set(value) { this.$emit("update:name", value); }
    }
  },
  methods: {
    resetname() {
      this.currentName = "updated from child";
    }
  }
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

Using the Facebook marketing API requires a valid Instagram account ID to be provided as a parameter

I've been exploring the capabilities of the Facebook Marketing API once again. After successfully creating Facebook ads using my Node.js app, I now have my sights set on Instagram. My current call to create an AdCreative looks like this: fb.api(&ap ...

Utilizing the power of Node.js with Oracle seamlessly, without the need for the Oracle Instant

Currently, I am working on testing the connectivity to our Oracle databases. Recently, I came across node-oracledb, a tool released by Oracle that aims to simplify this process. However, one major hurdle is the requirement of having the Oracle Instant Clie ...

Executing a Function within UseEffect

I need help calling the function onSaveInputValue within the useEffect to make sure that the value is passed to the childInputValue hook whenever the page loads. const onSaveInputValue = (value) => { setChildInputValue(value); consol ...

The jQuery functions seem to be malfunctioning when trying to retrieve elements by their ids

I'm having trouble with the click function when using IDs, but it works fine with classes. $('#myTab li a').click(function(e) {} When I switch to using classes like this: $('.nav-tabs a.overview').click(function(e) {} it work ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

Is caching a feature in AngularJS, and are there methods available for disabling it?

var modalInstance = $modal.open({ templateUrl: '/template/edit-modal.html', controller: ModalInstanceCtrl2, resolve: { locations: function () { return locationToEdit; } }, scope: $scope.$new() }); ...

AngularJS: Issue with ng-show and ng-click not functioning when button is clicked

I have a specific requirement where I need to display and hide the description of each column in a table when a button is clicked. Here is the visual representation of what I have: the table In my HTML code, I have defined a button with ng-click as a func ...

Determine if the "Enter" key has been pressed and validate the

How can I implement Enter key press functionality to login to the system using JavaScript? Below is the code snippet: @using (Html.BeginForm("Login", "InventoryBarcode", FormMethod.Post, new { id = "main" })) { <label for="LoginName" class="uname ...

What is the process for obtaining the URL of the website that is hosting my iframe?

Do you have a technical inquiry? I am curious to know if it is feasible to retrieve the URL of the website that is hosting my iframe. The pages that host my iframe are utilizing the following code: <iframe id="vacancy-iframe" src="http://mypage.co ...

Is reCAPTCHA v3 functioning properly?

My front end utilizes vuetify in this manner : validate: async function () { let tokenCaptcha await this.$recaptcha('login').then((token) => { tokenCaptcha = token }) if (this.$refs.form.validate() && tokenC ...

Is there a discrepancy in performance when running a function on an individual element versus a group of elements within jQuery?

Imagine having the choice between applying a function to an individual DOM element or a list of them: For Individual Elements: $('#element1').click(function () { $(this).hide(); return false; }); $('#element2').click(functi ...

Is there a way to execute a method from a child component in VueJS?

I'm trying to figure out how to make a parent component trigger a method in a child component when a button is clicked. Here's an example of what I have: Parent <template> <child-component></child-component> <button @clic ...

A guide on iterating through an array to extract the initial character from every string

Currently, my focus is on extracting the initial letter of each word in order to create an acronym. I have set up an array where all the capitalized words are stored, and now I need a way to extract those specific characters. To achieve this, I initially ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

Populate object values dynamically through function invocations

Currently, I am involved in a project with a VueJS application that incorporates the following helper class and method: class BiometricMap { static get(bioType) { if (!bioType) { return BiometricMap.default(); } const bioTypes = { ...

Incorporating Dynamic Events into HTML Generated on the Fly within a Vue.js Component

Currently, I am facing an issue where I am trying to dynamically generate HTML in a Vue.js component. While I have successfully rendered the HTML, I am struggling to connect the events for these dynamically generated elements. To illustrate this problem, I ...

Exploring the Vue 3 Composition API: Managing 'child' data within a tabbed component

Currently, I have a TabGroup/TabItem component that works with both Vue 3 and Vue 2, but it's built using the Options API. Now, I'm in the process of developing a new carousel component that shares many features with the TabGroup component. Howe ...

How can I disable a checkbox in AngularJS?

Is there a way to automatically disable a checkbox when selecting an item from the combo box? For example, if "ABONE" is selected, Angular should disable the ABONE checkbox. Note (for example): DefinitionType: ABONE https://i.sstatic.net/vcZpR.png ...