本文為大家分享了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怎么玩
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答