user13639694
user13639694

Reputation:

Share data between two child components Vue js

i am trying to send and render some data from a child component to another child component & both components are rendered using one main component , how can i pass the data between two child components (in my vue app)?

exg

I have two child components A & B , "B" has click add to cart click event and have data of cart items , & i have template for cart item in component "A"

Upvotes: 0

Views: 5019

Answers (3)

akim lyubchenko
akim lyubchenko

Reputation: 253

Ideally, you should use Vuex as state management pattern. But if your application is very simple and you don't need to do those operations often, you can pass data in emit payload from child to parent, and then parent component should pass it to another child via props

Upvotes: 0

Muni Kumar Gundu
Muni Kumar Gundu

Reputation: 532

There are a lot of ways to achieve this. I am explaining with global even bus concept. Following is an example. Here, child A and child B are communicating through event bus

const eventBus = new Vue ()

Vue.component('ChildB',{
  template:`
    <div id="child-b">
      <h2>Child B</h2>
      <pre>data {{ this.$data }}</pre>
      <hr/>
    </div>`, 
  data() {
    return {
      score: 0
    }
  },
  created () {
    eventBus.$on('updatingScore', this.updateScore)  // 3.Listening
  },
  methods: {
    reRender() {
      this.$forceUpdate()
    },
    updateScore(newValue) {
      this.score = newValue
    }
  }
})

Vue.component('ChildA',{
  template:`
    <div id="child-a">
      <h2>Child A</h2>
      <pre>data {{ this.$data }}</pre>
      <hr/>
      <button @click="changeScore">Change Score</button>
      <span>Score: {{ score }}</span>
    </div>`,
  props: ["score"],
  methods: {
    changeScore() {
    this.score +=200;
      eventBus.$emit('updatingScore', this.score+ 200)
    }
  }
})

Vue.component('ParentA',{
  template:`
    <div id="parent-a">
      <h2>Parent A</h2>
      <pre>data {{ this.$data }}</pre> 
      <hr/>
      <child-a :score="score"/>
      <child-b/>
    </div>`,
  data() {
    return {
      score: 100
    }
  } 
})


Vue.component('GrandParent',{
  template:`
    <div id="grandparent">
      <h2>Grand Parent</h2>
      <pre>data {{ this.$data }}</pre>
      <hr/>
      <parent-a/>
    </div>`,
})

new Vue ({
	el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <grand-parent/>
</div>

Upvotes: 0

Nilson Jacques
Nilson Jacques

Reputation: 468

In this situation, as both components share the same parent, it's common to move whatever shared state you need into the parent component and pass to the children as props.

Where components don't shared a direct parent, you can use an event bus (for very small apps) or Vuex. Vuex lets you share state between components in your app without having to pass props down through multiple levels.

Upvotes: 3

Related Questions