How can Vue.js transfer form data values (using v-model) from a Parent component to a Child component?

I am working on a multistep form using vue.js. The parent form collects two inputs and once these are validated, it moves to the next step which involves a child component. I want to pass the values from the parent component to the child component's formData object for submission. How can I achieve this without using $emit to trigger a function?

Parent Form:

<div class="row--flex">
            <input type="text" class="form-input text-input center-margin" name="deductibleCardId" id="deductibleCardId" v-model="$v.formData.deductibleCardId.$model" />
  
       <input type="text" class="form-input text-input center-margin" name="savingsCardId" id="savingsCardId" v-model="$v.formData.savingsCardId.$model" />
        </div>

//child component call
 <GetCard v-if="showDemographics" :is-sub-form="true" @submit="submitDemographics" />

 data() {
    return {
      formData: {
        hasCard: null,
        deductibleCardId: null,
        savingsCardId: null
      }
  }

Child Component FormData:

const formData = new FormData()

        formData.append('method', 'activate')

        (bring over these values from parent)

        formData.append('card_hd', this.formData.deductibleCardId)
        formData.append('card', this.formData.savingsCardId)

Answer №1

A great solution for passing data between parent and child components is to use Props. If you have two values, such as 'deductibleCardId' and 'savingsCardId', both being of String type, you can implement this setup:

Parent Component:

<GetCard :deductibleCardId='deductibleCardId' :savingsCardId='savingsCardId'>

Child Component:

props: {
  deductibleCardId: String,
  savingsCardId: String,
}

Using these props in your child component allows you to manipulate the values easily using this.deductibleCardId and this.savingsCardId. For instance, you could add them to a formData object like this:

formData.append('card_hd', this.deductibleCardId);
formData.append('card', this.savingsCardId);

When passing data from parent to child components, emitting events may not always be necessary. However, if you need to communicate data back to the parent component, consider using Vue's emit function or explore other communication strategies within the Vue ecosystem.

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

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

How to avoid console messages when dealing with Axios 422 error handling?

When developing my application, I decided to use Laravel for the backend and Vue for the frontend. To handle validation errors, I chose to implement code 422 based on recommendations from this article. The PHP code snippet in my RegisterController: if ($t ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

Encountering issues with installing Vue-edit-json through npm

While attempting to integrate the https://github.com/dirkliu/vue-json-editor editor into my project, I followed the instructions and executed npm install Vue-edit-json --save. However, I encountered the following error: Timocins-MacBook-Pro:s360auth timoc ...

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

AngularJS - Issue: [ng:areq] The 'fn' argument provided is not a function, instead it is a string

I encountered an issue: Error: [ng:areq] Argument 'fn' is not a function, received string Despite following the recommendations of others, I still have not been able to resolve the problem. Below is the code snippet in question: controller. ...

Generate a new item using an existing one

I am seeking to extract the desired output from the provided input: Input Configuration: var inputParams = { 'inputDetails' :[ { 'field' : 'specificationName', 'value' : 'strong'}, { ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Calculating the difference between the old scrolltop and the new scrolltop in jQuery/Javascript

I have a seemingly straightforward question, yet I am struggling to find a solution. Each time a user scrolls, the scrollTop value changes. I want to subtract the previous value from the new value of the scrollTop. However, I am unsure how to store the old ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Please use Shift + Enter feature only when using desktop devices

In my React chat application, I have implemented a textarea for message input to allow multiline support. This works smoothly on mobile devices as pressing Enter creates a new line and a send button is available to submit the message. However, I want a di ...

"The value of a variable in jQuery's 'animate' function can be dynamically adjusted

Looking to smoothly animate a variable using jquery. For example: Starting with a variable value of 1, we want it to reach 10 after 5 seconds. The transition should be smooth and increase gradually. I hope this clarifies what I am trying to achieve. Tha ...

Fetching a substantial amount of data via AJAX to generate a graph

Currently, I am in the process of developing a server that will supply data and information to both a web client and a mobile client in the second phase. One of the key features is displaying this data on a graph, such as showing the price of a stock over ...

Tips for managing the 'completed' button in an Android keyboard application using AngularJS/Ionic

Currently, I am working on developing a hybrid mobile application using AngularJS, Cordova, and the Ionic framework. Check out this Android 5.0 keyboard with a distinct blue button located at the bottom-right corner. https://i.stack.imgur.com/Tfija.png ...

Mapping the Way: Innovative Controls for Navigation

Currently, I am utilizing the HERE maps API for JavaScript. However, I would like to customize the design of the map controls similar to this: Below is an example for reference: HERE EXAMPLE Is it feasible to achieve this customization? ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...