oduwa
oduwa

Reputation: 13

How to pass a reactive variable from child component to parent component in vue js composition api

I have two components on is the parent component and the other the child component, the parent component has a form field in this form field I can add additional form fields, this additional form field is added with the aid of a component, the form field in the parent has its own reactive variable and the addition component also has its own reactive variable, so when am about to submit I need to capture the reactive variable details in the child component so I can pass it as a form to the api.

I have tried a lot of the videos on youtube, majority of the videos suggest I use the defineProps() method to capture data from parent component to child, but of all the videos non was given on how to capture data from child to parent, I tried the method if it will work vice versa but it did not.

Upvotes: 1

Views: 4048

Answers (1)

Tolbxela
Tolbxela

Reputation: 5181

Check the answers:

For Data Sharing between components you can use Custom Stateful Store Object or Pinia.

Check the Vue Docs on

Here is a very basic example of Custom Stateful Store Object

const { createApp, ref, toRef, toRefs } = Vue;

const myStore = {
  counter: ref(0),
  add: function() {
    this.counter++ 
  }   
}

const template = 'counter = {{counter}}<br/>' 

const CompA = {
  setup() {
    const { counter } = myStore
    return  { counter }
  },
  template: template
}

const CompB = {
  setup() {
    const { counter } = myStore
    return  { counter }
  },
  template: template
}

const App = {
  components: { CompA, CompB },
  setup() {
    const { counter, add } = myStore
    return  { counter, add }
  }
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app">
  CompA: <comp-a></comp-a>
  CompB: <comp-b></comp-b>
  App: counter = {{counter}}<br/>
  <button @click="add()">+1</button>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Upvotes: 0

Related Questions