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

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

The comparison between AJAX and JSON passing and PHP generating HTML versus returning it

Currently, my code looks like this: <li onclick = " function CBAppData( callerObj, data ) { var string = ''; for( a in data ) { debug.push( data[ ...

Creating an image on an HTML canvas using RGB values

Looking for assistance on displaying an image using HTML Canvas with three 12x12 arrays containing R, G, and B values. I've seen Canvas demos showing how to draw lines, but nothing on using RGB arrays to create an image. Any tips or guidance would be ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

dispatch.yaml - Issue with Accessing Subdomain in App Engine Standard Environment

After deploying my static webpage on App Engine, I encountered an issue when trying to access it through a custom subdomain. The CSS and JavaScript files were not loading properly, resulting in the Vue.js application failing to load as intended. Despite s ...

Creating a typewriter effect with Vue Js

Hey there, I'm having some trouble with the code below while working on my Vue project. It seems to be functioning correctly, but for some reason it's not working in my Vue environment. const text = document.getElementById("text"); const phrase ...

Error: scrollreveal JavaScript is not properly defined

Desperately seeking guidance on a particular code snippet... window.sr = ScrollReveal({ reset: true }); sr.reveal('.whitecircle, .circleStatsItemBox, .circleStat', { duration: 200 }); function circle_program() { var divElement = $(&apo ...

"Expo Securestore is encountering an issue where it is unable to store the user ID and token following authentication

I am currently working on securely storing the userId and token in SecureStore. I have successfully retrieved the token from SecureStore on the next screen, but for some reason, I am unable to see the userId. const doUserLogIn = async() => { try { ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Solving Unique Data Types Directly in the Root of GraphQL

It seems like there's an obvious solution missing. I have IDs stored as [String] that I need to resolve to their corresponding full objects. Context This is the functionality I aim to achieve, but the crucial aspect missing is the resolvers: const ...

What are the steps for implementing this javascript code in an HTML document?

Recently, I've been seeking advice on how to address the issue of wanting a button click to automatically select the search box on my website. Suggestions have pointed towards using Javascript for this functionality, with the following code recommend ...

Ensure to verify the dimensions and size of the image prior to uploading

Is there a way to check the dimensions of an image using this function? I want to verify it before uploading... $("#LINK_UPLOAD_PHOTO").submit(function () { var form = $(this); form.ajaxSubmit({ url: SITE_URL + 'functions/_app/execute ...

Converting TypeScript to JavaScript: A Step-by-Step Guide

I have this code written in Typescript and I need to convert it to JavaScript const Home = (props) => { return ( <div> {props.name ? 'Hi ' + props.name : 'You are not logged in'} </div> ); }; How can I re ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

Discover the steps to incorporate an external JS file into Next.js 12

I am encountering an issue in my Next.js project when trying to import a local JS file. Here is the code snippet I am using: <Script type="text/javascript" src="/js.js"></Script> Unfortunately, this approach results in the ...

Create an AngularJS directive that formats the model value for visual display, while retaining the original value in the model

I am facing a challenge in building an AngularJS directive for a currency textbox. The directive should take values (amount and currency code) from the model in the scope and then apply currency formatting to it. I am struggling to build this directive usi ...

Passing data back from an asynchronous function to its parent function in Node.js

Exploring the world of asynchronous programming is a new adventure for me as I delve into implementing Twilio video calls through Node.js. I've been grappling with calling a server-side function that in turn invokes another asynchronous function retu ...

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...