How to call a child function from a parent component in Vue.js and retrieve data

While developing a step form, I encountered the need to validate and retrieve data from my child component.

The step form is divided into a parent container and a child component (Step 1).

The child component contains form data as follows:

<template>
     This is where the form fields are located
</template>
<script>
 data:()=>({
    orderform:{
      first_name:'',
      lastname:''
    }
  }),

methods:{

 submitOrder(){
  this.$validator.validateAll()
     .then(
      (res)=>{
        if(res){
           //pass this.orderform to parent component

         }   

       }
      )

  }


 }

In the parent component, I am struggling to execute the function in the child component and access data from the parent. See the updated parent structure below:

<stepper>
 <v-stepper-content step="1">
         <child-1></child-1>
    <button  @click.native="gotonextStep">Continue</v-btn>
  </v-stepper-content>
  ...other stepper steps
</stepper>

Answer №1

Utilize a vue reference

<child-component ref="child1"></child-component>

Subsequently, within the parent component, you have the ability to invoke methods or retrieve data from the child component:

methods:{
  goToNextStep(){
     // call method in child component
     let result = this.$refs.child1.someChildMethod()
     // access data properties within the child component
     let data = this.$refs.child1.someChildDataProperty
  }
}

Answer №2

CHILD Component

completePurchase(){
  var self = this;
  this.$validator.validateAll()
     .then(
      (result)=>{
        if(result){
           //send this.purchaseform to the parent component
           self.emit('childConfirmed',this.purchaseform);

         }   

       }
      )

  }

Parent Component

<purchased-component @childConfirmed="proceedToNextStep"></purchased-component>

steps:{

proceedToNextStep(dataFromChild){
   //call completePurchase function here
   //need assistance with implementation
   //also fetch purchase form data in this section.
}
} </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

Can Selenium in C# effectively test file dragging and dropping in FireFox?

We have implemented a drag and drop file script on our website using for handling FireFox and Chrome drag and drop file uploads. Our team is currently working on integrating selenium tests to ensure the overall functionality of the site. I am wondering ...

Troubleshooting 'Warning: Prop `id` did not match` in react-select

Having an issue with a web app built using ReactJs and NextJs. I implemented the react-select component in a functional component, but now I'm getting this warning in the console: Warning: Prop id did not match. Server: "react-select-7 ...

What is the best way to make an element's width match the width of the window?

When using the following code: $(my_div).width(window.innerWidth) The expected result is not achieved, as it does not take into account the vertical scrollbar. This causes the element to overflow the window, resulting in a horizontal scrollbar, which ca ...

What is the best way to style the current element being targeted in React?

In my React application, I am trying to dynamically adjust the height of a textarea element based on its content. I want to achieve this by utilizing an 'onchange' listener to trigger a resize function. While I have successfully implemented the ...

Do JavaScript have dictionary functionality similar to Python?

I am trying to create a dictionary in JavaScript that looks something like this: I can't recall the exact syntax, but it was similar to: states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } Does JavaScript support this ty ...

select2 typeahead options for preloaded data

Utilizing Select2 on a select menu presents a challenge where the search field displays options even if the typed letters appear in the middle of an option. As an example, consider a select menu with options for Apple, Grape, and Prune: <select id="e1 ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

Trying out REST endpoints using curl's -X PUT command results in a 404 error code

Currently, I am delving into the realm of the MEAN stack and following along with the MEAN tutorial provided by thinkster.io. You can find the tutorial here: As of now, I am navigating through the "Opening REST Routes" section. In an attempt to PUT an upv ...

The best way to distribute React components within a monorepo using source sharing

I am managing a monorepo with 3 unique React projects: - SHARED_COMPONENTS src Button.tsx package.json - APP_A src main.ts package.json - APP_B src main.ts package.json How can I import the Button(.tsx) module in both main.ts files ...

Show picture depending on the button pressed

Is it possible to only display the selected image? I have a set of buttons that allow customers to customize an image. For example, the user selects a shape like a circle, which is then displayed. The next step involves selecting a pattern to display insi ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Opposition.js conditional graph insertion

Currently, I am in the process of developing an import feature for our software that allows users to import data from Excel files into the system. We utilize objection.js (a creation tool) and I am using the insertGraph() method to insert content. My main ...

Resize image to fit the window, and subsequently switch between full size and adjusted size upon clicking

I need assistance in creating a code snippet that will automatically adjust the size of an image to fit the user's screen resolution. Additionally, I want to provide users with the option to toggle between viewing the actual image size and the adjuste ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

Calculate the duration of '1 hour 30 minutes and 4 seconds' as a future time in JavaScript

If I have a string like 1hr 30m 4s, how can I utilize Node.js to convert it into a future time from the date of execution? I've explored NPM libraries such as date-fns and moment, but they don't appear to offer the functionality I need. Perhaps ...

Measuring JSON data with PHP through asynchronous requests

Looking to retrieve a specific count from a json dataset. Here is an example json format: { "tickets": [ { "url": "https://asd.zendesk.com/api/v2/tickets/1.json", "id": 1, "external_id": null, "via": { "channel": "sa ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Transform JavaScript code to integrate with a pre-existing WebSocket within a React.js application

I have created a JavaScript code to establish connections with my own Ruby WebSocket server, where it waits for incoming messages, parses them, and then displays content based on certain conditions (the implementation details are not relevant at the moment ...

Implementing Material-UI select to utilize an object as a value and showing corresponding text upon selection

Utilizing an API, I am mapping data to generate a grid of dropdown options (mui select). When the value changes, two values should be recorded. To achieve this, I have created an object with all the necessary fields that update when a user changes a selec ...

Disable the ng-change event

Is there a way to prevent the ng-change event from happening? I have a select box with an option that I don't want users to select. Instead, I want to display a warning message and then revert back to the previously selected option. To achieve this, ...