简体   繁体   中英

How to access child component data in parent component vueJs?

I am having Vue Application and I am loading different child component's based on the values selected from parent component . When I am clicking on submit button which is in parent component I want to get all the values of child component into parent.

<template>
<div>

<v-select v-model="category"/>


<firstComponent v-show="category == 1">
<secondComponent v-show="category == 2">

<v-btn @click="submitData">Submit</v-btn>
</div></template>

Please ignore syntax. I want all the input field data of child component into submitData method of parent component.

<template>
   <child ref="children">
</template>


this.$refs.children.anything

https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements

You can use scoped slots for that, something like inside firstComponent :

<slot :data="sharedData">
// you could display stuff here but not mandatory
</slot>
// in parent
<firstComponent>
 <template v-slot="{sharedData}">
....

now you have access to shared data, you can provide that to your submit function.

Concept of VueJS can access children component via VUEJs component id, but is troublesome. Suggestion is use 1. EventBus https://alligator.io/vuejs/global-event-bus/ (try to avoid for using this because it is hard to trace where your event need to listen and call when your front end code is have hundred of files) 2. Vuex which is more appropraite for VueJS web development purpose

There are different ways available for sharing data in Vue. You can use serverbus, vuex or in case of child-parent relation you can simply emit the data from child to event.

For your specific case, I'd suggest you to have an object/array in the parent component which would be passed down as a prop to all the child components and then have the form values binded to the keys in the object. Since the arrays/objects are passed by reference the value changed would be directly available in the parent component. However, if you're comfortable with Vuex then opt for the same.

Also, I feel you should use dynamic components to render your component as your category is changing otherwise you'd have a number of v-show or v-if in your code when the components would increase. ( https://v2.vuejs.org/v2/guide/components-dynamic-async.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM