Vue - 非父母子女沟通

时间:2017-11-24 14:06:26

标签: javascript vue.js components emit

阅读Vue文档时 Non parent-child communication
为了练习,我试图建立一个例子,看它是否有效,下面是我的代码:
我构建了两个组件,并尝试使用Vue实例总线在点击时将消息从dudi-station传输到dudo-station,但它不起作用。
有人可以帮忙吗?谢谢!



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',
})
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <dudi-station></dudi-station>
  <dudo-station></dudo-station>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

因为在这句话中: bus.$on('callout', function(value) { this.dudoMsg = value; 并不代表您的vue实例。 你需要使用箭头功能来确保这个&#39;这个&#39;表示vue实例。 如下所示:

&#13;
&#13;
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',
})
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <dudi-station></dudi-station>
  <dudo-station></dudo-station>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

从另一个组件接收组件中的消息时,请使用箭头功能作为事件处理程序。它将帮助您使用“ this”关键字范围。

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

而不是按以下方式使用它

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