Saeed Vaziry
Saeed Vaziry

Reputation: 2355

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 and after it done the below line runs
        this.$emit('foo', 'bar');
    }
});

Child Component

<template></template>
<script>
    export default {
        created: function() {
            this.$on('foo', function(data) {
                console.log(data);
            });
        }
    }
<script>

It's not working.

Is there any way to broadcast some data to all child components from root?

Upvotes: 1

Views: 2390

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

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>

Upvotes: 1

Gru Sarn
Gru Sarn

Reputation: 1

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)
  }
})

Upvotes: 0

Related Questions