[Vuejs]-Share data between two child components Vue js

0👍

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>

3👍

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.

0👍

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

Leave a comment