這篇文章主要介紹了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=""; } },
感謝你能夠認真閱讀完這篇文章,希望小編分享的“vuejs事件中心管理組件間通信的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。