Skip to content Skip to sidebar Skip to footer

How To Broadcast To All Components From Root Vue.js

I want to $emit some data to all child components in vue.js 2 and this is my code : Root Component const app = new Vue({ created: function(){ // here is some promise an

Solution 1:

Vuejs is bottom up approach, means child component is compiled first and ask for this.$on so broadcasting will not work here with $emit-$on

Use props in child component to watch root data changes, giving this example where child1 and child2 having same root component data named name

var child1 = Vue.extend({
    template: "<div>Child Component1 : Niklesh : {{name}} <div v-if='loading'>Loading...</div></div>",
    props: ['name','loading']
});
var child2 = Vue.extend({
    template: "<div>Child Component1 : Rishi : {{name}} <div v-if='loading'>Loading...</div></div>",
    props: ['name','loading']
});
var app = new Vue({
    el: "#vue-instance",
    data: {
        name: "...",
        loading: true
    },
    mounted() {
    		var vm =  this;
    		setTimeout(function() {
        	vm.name = "Raut";
          vm.loading = false;
				}, 1000);
    },
    components: {
        child1,
        child2
    },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
    <child1 :name="name" :loading="loading"></child1>
    <child2 :name="name" :loading="loading"></child2>
</div>

Solution 2:

Use another Vue instance as an Event bus

Code Pen Sample

<div id="app">
  <child></child>
</div>

var bus = new Vue()

Vue.component('child', {
  data() {
    return {
      message: 'waiting for event...'
    }
  },
  template: '<div>{{ message }}</div>',
  created: function() {
    bus.$on('foo', data => {
      this.message = data;
    })
  }
})

var app = new Vue({
  el: '#app',
  created: function() {
    setTimeout(()=> {
      bus.$emit('foo', 'bar')
    }, 1000)
  }
})

Post a Comment for "How To Broadcast To All Components From Root Vue.js"