What is the most effective way to transfer data from a child component to a parent component when the child component contains multiple input fields?

Passing data from a parent component to a child component is something I need help with. Let's say I have a parent component with the following data:
Parent component

<template>
         
   <NameUser :data="userData"></NameUser>
   <div>first name: {{ userData.firstName }}</div>
   <div>last name: {{ userData.lastName }}</div>
 
</template>

<script setup>
    
    import {ref} from 'vue'
    import NameUser from '../components/NameUser.vue';
    const userData = ref({
        firstName: 'testName',
        lastName: 'testLastName'
    })

</script>

The child component will receive this data and then send it back to the parent component once modified.
Child component

<template>

    <label>First name</label>
    <input :value="data.firstName" @input="changeData">

    <label>Last name</label>
    <input :value="data.lastName" @input="changeData">

</template>

<script setup>

    const props = defineProps({
        data:Object
    })

    function changeData(){}

</script>

I would appreciate assistance in implementing the changeData function. Additionally, guidance on whether using a computed property to prevent re-rendering is necessary would be helpful.

Answer №1

SFC Playground

You have the option to utilize a distinct reactive object within NameUser for updating it from inputs and maintaining synchronization with a model value. This allows additional inputs to be added without needing to declare extra variables.

It is worth noting that your changeData function does not receive any additional parameter to differentiate between different properties in the user object. It is recommended to use v-model on inputs instead, as this simplifies the process significantly.

NameUser.vue

<script setup>

    import {reactive, watch} from 'vue';
    const props = defineProps({
        modelValue: Object
    });

    const value = reactive({});
    const emit = defineEmits(['update:modelValue']);
    
    // 2-way binding - watch for prop changes
    watch(() => props.modelValue, data => Object.assign(value, data), {immediate:true});
    // create a copy of value so the above watch trigger
    wouldbe 
      watch(value, value => emit('update:modelValue', {...value}));

</script>
<template>

    <label>First name</label>
    <input v-model="value.firstName">

    <label>Last name</label>
    <input v-model="value.lastName">

</template>

Parent.vue:

<script setup>
    
    import {ref} from 'vue'
    import NameUser from './NameUser.vue';
    const userData = ref({
        firstName: 'testName',
        lastName: 'testLastName'
    })

</script>

<template>

   <NameUser v-model="userData"></NameUser>
   <div>first name: {{ userData.firstName }}</div>
   <div>last name: {{ userData.lastName }}</div>

    <br/>
   <div>Check 2-way binding:</div>
   <NameUser v-model="userData"></NameUser>
 
</template>

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

Creating a versatile function for rendering content

I am working on a unique calendar feature that involves using checkboxes for filtering purposes. So far, I have managed to get all the filters functioning correctly by triggering my render event in this manner: //Initiate render event when checkbox is cli ...

How to leverage Vue Selectize to fetch JSON data from dropdown options?

I have integrated vue2-selectize to showcase a list of options fetched via an axios call: <template> <selectize v-model="selected" :settings="settings"> <option v-for="option in options" :value="option.id"> ({{ op ...

Multiple occurrences of the cookie found in the document.cookie

My client is using IE9 and the server is asp.net (specifically a SharePoint application page). Within the Page_Load method of a page, I implemented the following code: Response.Cookies["XXXXX"].Value = tabtitles.IndexOf(Request.Params["tab"]).ToString(); ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

Step by step guide to verifying email addresses with Selenium WebDriver

A feature in my EXTJS application includes a page with an Email button. When this button is clicked, it generates a link to the page contents and opens the default email client with this link in the body. Upon inspecting the DOM, I found that the Email bu ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

Is there a way to escape from an iFrame but only for specific domains?

if (top.location != self.location) { top.location = self.location.href; } If my website is being displayed in an iFrame, this code will break out of it. But I want this to happen only for specific domains. How can I perform that check? ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

What is the best way to loop through ng-repeat with key-value pairs in order to display each

I need to loop through and show the data stored in "detailsController". <div ng-controller="detailsController"> <div ng-repeat="data in details" id="{{data.Id}}"> {{data.Name}} </div> </div> ...

Avoid Scroll Below Stuck Navigation

I've been searching for a solution to my issue for some time now, and while I've come across many articles discussing similar problems, none of them seem to address my specific problem. In my React app, I have a mobile version where users can ta ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

Ways to expose a components prop to its slotted elements

I've set up my structure as follows: <childs> <child> <ul> <li v-for="item in currentData">@{{ item.name }}</li> </ul> </child> </childs> Within the child component, t ...

Exploring the nuances of receiving responses with NextJs, Nodemailer, and Fetch

Currently in the process of constructing a basic contact form with Next.js, nodemailer, and fetch. Despite successfully sending emails from the frontend form to the designated email account, the network shows the contact submission as pending. After approx ...

An operator in rxjs that transforms an Observable of lists containing type X into an Observable of type X

Currently, I am facing a challenge while dealing with an API that is not very user-friendly using Angular HTTP and rxjs. My goal is to retrieve an Observable<List<Object>> from my service. Here's a snippet of the JSON output obtained from ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

The error message being displayed states that 'null' cannot be used as an object when evaluating 'response.productType'

Hey everyone, I'm fairly new to working with Ajax and I've encountered an error in my code that says: TypeError: 'null' is not an object (evaluating 'response.productType'). I'm not sure why this is happening. Below is th ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...