vuejs事件中心管理組件間的通信詳解
本文為大家分享了vuejs事件中心管理組件間的通信,供大家參考,具體內(nèi)容如下
事件中心
這個(gè)可以是一個(gè)空的全局的Vue實(shí)例,其他的組件利用這個(gè)實(shí)例emit和on自定義事件,這樣組件定義了自己的事件處理方法。
import Vue from 'Vue' window.eventHub = new Vue();
事件監(jiān)聽和注銷監(jiān)聽
事件監(jiān)聽?wèi)?yīng)在更組件的created鉤子函數(shù)中進(jìn)行,在組件銷毀前應(yīng)注銷事件監(jiān)聽
//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: 這其實(shí)還不是最理想的通信方式,下一篇我們看看vuex怎么玩
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue使用動(dòng)態(tài)組件實(shí)現(xiàn)TAB切換效果完整實(shí)例
在實(shí)際項(xiàng)目開發(fā)中,我們經(jīng)常會(huì)遇到選項(xiàng)卡切換,對(duì)于一個(gè)前端工程師來說,組件化/模塊化開發(fā)是一種必備的行為規(guī)范,下面這篇文章主要給大家介紹了關(guān)于vue使用動(dòng)態(tài)組件實(shí)現(xiàn)TAB切換效果的相關(guān)資料,需要的朋友可以參考下2023-05-05
vue本地打開build后生成的dist文件夾index.html問題
這篇文章主要介紹了vue本地打開build后生成的dist文件夾index.html問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-09-09
構(gòu)建大型 Vue.js 項(xiàng)目的10條建議(小結(jié))
這篇文章主要介紹了構(gòu)建大型 Vue.js 項(xiàng)目的10條建議(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

