当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vuejs事件中心管理组件间的通信详解

vuejs事件中心管理组件间的通信详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

3u8579,李鸾英,辛亥革命邮票

本文为大家分享了vuejs事件中心管理组件间的通信,供大家参考,具体内容如下

事件中心

这个可以是一个空的全局的vue实例,其他的组件利用这个实例emit和on自定义事件,这样组件定义了自己的事件处理方法。

import vue from 'vue'
window.eventhub = new vue();

事件监听和注销监听

事件监听应在更组件的created钩子函数中进行,在组件销毁前应注销事件监听

 //hook 
 created: function () {
 //listen event
 window.eventhub.$on('switchcomments',this.switchcomments);
 window.eventhub.$on('removeissue',this.removeissue);
 window.eventhub.$on('savecomment',this.savecomment);
 window.eventhub.$on('removecomment',this.removecomment);

 //get init data
 var that =this;
 axios.get('issue/index')
 .then(function (resp) {
  that.issue_list=resp.data;
 });
 },
 beforedestroy: function () {
 window.eventhub.$off('switchcomments');
 window.eventhub.$off('removeissue');
 window.eventhub.$off('savecomment');
 window.eventhub.$off('removecomment');
 }

子组件的emit事件,注意这里用的window.$emit而不是this.emit

 methods: {
 removecomment: function(index,cindex) {
  window.eventhub.$emit('removecomment', {index:index, cindex:cindex});
 },
 savecomment: function(index) {
  window.eventhub.$emit('savecomment', {index: index, comment: this.comment});
  this.comment="";
 }
 },

note: 这其实还不是最理想的通信方式,下一篇我们看看vuex怎么玩

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网