Mapping Data Dynamically Between Parent and Child Components with Vue.js

It seems like I am headed towards a path of inefficiency when it comes to keeping data properly synced between Parent and Child components.

For instance, if I have a basic Child Vue element like the one below:

common/InputText.vue

<template>
    <input v-bind:id="name" v-bind:value="value" v-on:input="changed($event, $event.target.value)">
</template>

<script>
    props: ['name', 'value'],
    methods: {
        changed(event, value) { this.$emit('emitChanged', event, value); }
    }
</script>

If I then use a Parent Vue element like the example below, where data is being bound to the Child elements, I encounter an issue. It appears that the binding only works from the Parent to the Child, with changes in the Parent not reflected in the child component.

Parent.vue

<input-text name="field01" v-bind:value="field01" @emitChanged="changed"></input-text>
<input-text name="field02" v-bind:value="field02" @emitChanged="changed"></input-text>

<script>
    import inputText from "./common/InputText.vue";
    export default {
        data() {
            return() {
                field01: '',
                field02: ''
            }
        },
        components: {
            input-text: inputText
        },
        changed(event, newValue) {
            console.log(newValue);
        }
    }
</script>

To update the Parent data based on what the Child returns, I currently rely on modifying the changed method as shown below:

changed(event, newValue) {
    console.log(newValue);
    if( event.target.id == 'field01' ) {
        this.field01 = newValue;
    }
    if( event.target.id == 'field02' ) {
        this.field02 = newValue;
    }
}

While this approach works, it feels like a workaround and could become unwieldy when dealing with multiple input fields. What would be the proper way to ensure seamless updates between Parent and Child components?

Answer №1

Here is a clever technique to address your issue by avoiding the use of v-model. However, it is still recommended to consider utilizing v-model for a smoother implementation.

<template>
    <input v-bind:id="name" v-bind:value="value" v-on:input="changed($event, $event.target.value)">
</template>

<script>
    props: ['name', 'value'],
    methods: {
        changed(event) { this.$emit('emitChanged', event); }
    }
</script>
<input-text name="field01" v-bind:value="field01" @emitChanged="changed($event, 'field01')"></input-text>
<input-text name="field02" v-bind:value="field02" @emitChanged="changed($event, 'field02'"></input-text>

<script>
    import inputText from "./common/InputText.vue";
    export default {
        data() {
            return() {
                field01: '',
                field02: ''
            }
        },
        components: {
            input-text: inputText
        },
        changed(event, field) {
            this[field] = event.target.value
        }
    }
</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

When using vue-router push, the first page should not be concealed even if the data array is extensive

After navigating from Home.vue to History.vue using this.$router.push("/history/" + fileid);, a socket.io request is triggered in the created or mounted lifecycle hook which fetches a large amount of data. The rendering process, especially with v-for, take ...

Tips for resolving the error code 'ERR_REQUIRE_ESM' when working with code: to correct this issue, make sure to include the necessary library using the 'require' statement in the correct

How can I resolve this issue? I am working on an App chat project. Apologies if my language is hard to understand, as I am Thai. PS C:\Users\ADMIN\Desktop\chat\server> node server.js C:\Users\ADMIN\Desktop\ch ...

Confusion arises from the shadcn/vue configuration of Electron's source files

I currently have two src/components (assets) - one in the root directory and the other in /renderer. The component in the root directory was generated when I included resizable components using "npx shadcn-vue@latest add resizable" command, but something ...

What are the steps to delete data in angularjs?

I attempted to eliminate the data utilizing indexOf in AngularJS. Unfortunately, the remove function isn't functioning properly. Please guide me on identifying the mistake I may be making. JavaScript: var app = angular.module('myApp', []); ...

Navigating to a destination with react-leaflet: step-by-step guide

As a newcomer to React and Leaflet, I am trying to create a feature where users can input coordinates, trigger an event on pressing enter, and then have the map fly to those generated coordinates. I am successfully generating the latitude and longitude coo ...

The jQuery form validator doesn't seem to work with AJAX for me, but I've figured out how to make jQuery validate without using

I have been facing an issue with my code that involves the jquery validator and ajax. The code seems to validate properly and the serialize() function appears to be working as I can see the data in the browser. However, the problem arises when the data d ...

Can I change the names of the data retrieved from this API?

I'm looking to customize the names fetched from an external API in my <span>{{stats.team.name}}</span>. Currently, the output displays full club names like: Manchester City FC Manchester United FC Wolverhampton Wanderers FC Instead, ...

"Recently, I included a function called 'test' in the code, but I encountered an error stating that it was not recognized as a function. Can someone provide assistance

Issue Detected A 'TypeError' has been thrown: ".goal_test".click is not defined as a function Feel free to collaborate on the code by clicking this link: Please note that my modified code is enclosed within asterisk symbols. ...

Is there a way I can implement jQuery animation on my pop-up window?

I've successfully set up a basic popup using jQuery. When a button is clicked, it changes the 'display' property of a div from 'none' to 'block' in CSS and creates an overlay to darken the background. Take a look at my c ...

Get the title text from a selected div and create an array using JQuery

I'm attempting to gather the text from all divs' Title Attributes and store them in an array, but I'm having trouble finding the correct selection. The title is important because it holds the specific string that I require. Below are three ...

Tips for concealing a tooltip once a checkbox becomes enabled

I want to show a tooltip only when a checkbox is disabled. Once the correct format is typed into an input text field, the checkbox should become enabled. Currently, I am able to display the tooltip when the checkbox is disabled, but it does not hide when ...

Using Typescript to dynamically change the array being called based on a given parameter

How can we access different arrays based on the parameters passed? public array1: Array<any> = ['list', 'of','array1']; public array2: Array<any> = ['list', 'of','array2']; public a ...

Creating a digital item in a nested category using Mogoose

Within the realm of mongoose, there exists an object by the name of 'target' which houses an image (consisting of a name and extension). Each individual 'target' object also possesses a sub-collection of other objects, each containing t ...

Ajax external variable

I successfully uploaded a json file via Ajax using vanilla JS. { "list": [ {"name": "Executor", "date": "19.04.2017, 12:32:57"}, ... ] } Although I am able to change the "date" value for the current one using addEventListener, my challenge no ...

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving https://i.sstatic.net/aIKkO.jpg Here is the code snippe ...

Steps for identifying the file format of a document with JavaScript

Can someone assist me in determining a file type using JavaScript within the context of this HTML code? <div class="indi-download"> <div class="pull-left"> <h6 class="file-format">%file_display_name%</h6> </div> <div c ...

ReactJS - Continuous Loop invoking Encapsulated Function

I keep encountering the same issue with an infinite loop in my code, but I can't figure out why. Currently, I am working with reactJS version 16.5.2 The infinite loops tend to occur when you try to use SetState where it is not allowed (such as in th ...

Unable to locate module post npm installation

My Node.js application is running on an Ubuntu server hosted on Microsoft Azure. The package.json file for my project includes various dependencies required for the app to function. { "author" : "Coop", "name" : "app-framework", "main" ...

Ways to condense list chart into a single item and utilize a select dropdown to display choices without the need to refresh the

As a novice in the realm of creating charts using pandas and converting them into JSON format, I am faced with the challenge of displaying numerous graphs while conserving space. I am seeking guidance on how to implement a filtering system to only show the ...

Having trouble loading @ng-bootstrap/ng-bootstrap in Angular?

Currently, I am attempting to integrate @ng-bootstrap/ng-bootstrap with Angular and Electron while using Gulp in my project. Below is the content of my renderer.ts file: /** * Angular Module declaration */ let Brow ...