0

When reading Vue document Non parent-child communication
For practice, I tried to build an example to see if it works, below is my code:
I build two component and tried to use Vue instance bus to transport message from dudi-station to dudo-station while on-click, but it's not working.
Can anyone help? Thanks!

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', function(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>
tony19
  • 125,647
  • 18
  • 229
  • 307
Arel Lin
  • 908
  • 2
  • 13
  • 24

2 Answers2

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>
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Suyanhanx
  • 98
  • 5
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);
});
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129