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

Determining the size of an image prior to uploading it in a React

The solution for this issue can be found using vanilla JavaScript here To clarify, instead of using alert(), my goal is to store the dimensions in the state object. How can I adapt this code into a React component utilizing the OnChange() event handler? ...

Setting a cookie using express.js with a 'j' prefix

Trying to establish a cookie using res.cookie as shown below: res.cookie('userId',req.user._id); //cookie set here console.log(req.user._id); //correct value returned, eg abc However, I'm noticing j:"abc" in my cookie. What could be the re ...

Exploring the power of Next JS by implementing server-side rendering with a

I am faced with the challenge of incorporating navigation into my layout by utilizing data from an API and then displaying it on specific pages. The catch is that the Layout file is not located in the pages folder, meaning I cannot use traditional getStati ...

Dispatching actions in `componentDidMount` is restricted in Redux

Update at the bottom of post I've created a React container component called AppContainer, which checks if the user is authenticated. If the user is authenticated, it renders the app's routes, header, and content. If not, it displays a Login com ...

Increase the count for each category with the help of JavaScript

Currently, I am working on an application using PHP and have 180 vendors registered in the database. Each vendor has a unique ID stored in the database. I need to create a system where every time a user clicks on the "view details" button for a specific ...

ReactJs - Organize your data with the sort method

In my React application, I have a table that fetches its data from an API. I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash). Below is the sort function I ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

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'}, { ...

Uploading multiple files with Laravel 8, Vue.js, and Axios

I'm currently working on a project where I need to upload multiple files using axios and vue. Instead of using a form, I decided to update each field dynamically with this template: <input @change="setFiles" ref="files" n ...

moving a simulated element to a new location

Looking for some help with my html/CSS code that creates a unique element at the bottom of a div with an image background. The shape I've created is positioned at the bottom of the div... Below is the HTML: <div style="background-image:url(&apos ...

Gulp encountered an issue - Module 'sigmund' not found

After installing browser-sync, my previously working Gulp encountered an error: Error: Cannot find module 'lru-cache' To resolve this issue, I utilized the following solution: npm link lru-cache as suggested in this thread However, upon atte ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...

What is the most efficient way to add an attribute in jQuery - using the attr() method, passing attributes as a key-value object, or directly?

There are three ways that I am aware of for adding a href attribute with a relative link in jQuery: using (1) .attr(), (2) attributes as key-value pair in an argument, or (3) direct writing (if you know other methods, please share in your response so I can ...

Looking to verify a disabled select element and adjust the opacity of that element when it is disabled

$_product = $this->getProduct(); $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); ?> <?php if ($_product->isSaleable() && count($_attributes)):?> <dl> <?php foreach($_attrib ...

Insert a numerical value into a list to make a series of numbers whole

I currently have an array of objects that looks like this: var arr = [ { "code": "10", }, { "code": "14", } ] My goal is to expand this array to contain 5 elements. The numbers should ran ...

A step-by-step guide to creating a clipboard stream using guacamole-common.js

When utilizing Guacamole.client.createClipboardStream to generate a clipboard stream and sending the stream on paste event, I noticed that the remote clipboard remains empty. const customStream = client.createClipboardStream("text/plain"); cust ...

Discovering the automatically generated routes in Nuxtjs

Can I access the route list created by Nuxt.js based on pages folder items? The issue is that I am unsure of the exact route name generated for each component. $router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } }) This ...

Is the image flickering non-stop when the button is pressed?

Every time I push the button, the image on the HTML 5 canvas flickers. After investigating, it seems like the issue might be related to the ctx.clearRect(0,0,100,500) function. Any suggestions on how to fix this problem? I'm currently working on anim ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...