[Vuejs]-Vue – non parent child communication

0👍

Because in this statement:

bus.$on('callout', function(value) {
  this.dudoMsg = value;

this this is not mean your vue instance.
You need to use arrow function to make sure that ‘this’ means the vue instance.
Like below:

Vue.component('dudi-station', {
  template: '<div @click="sentMsg">{{dudiMsg}}</div>',
  data: function() {
    return {
      dudiMsg: 'Dudi!!',
    }
  },
  methods: {
    sentMsg: function() {
      bus.$emit('callout', this.dudiMsg);
    },
  }
});

Vue.component('dudo-station', {
  template: '<div>{{dudoMsg}}</div>',
  data: function() {
    return {
      dudoMsg:'',
    }
  },
  created: function() {
    bus.$on('callout',value => {
      this.dudoMsg = value;
      console.log(value);
    });
  }
});

var bus = new Vue();
new Vue({
  el: '#app',
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <dudi-station></dudi-station>
  <dudo-station></dudo-station>
</div>

0👍

Use arrow function as event handler when receiving message in component from another component. It will help you with "this" keyword scope.

bus.$on('callout', function(value) {
  this.dudoMsg = value;
  console.log(value);
});

instead of this use it as below

bus.$on('callout', (value) => {
  this.dudoMsg = value;
  console.log(value);
});

Leave a comment