1. 程式人生 > >vue非父子組件通信

vue非父子組件通信

關於 nts mit data cti 如何 flow clas -s

關於vue非父子組件如何通信,今天做了一個基本的例子,記錄下來。 使用一個空的vue實例作為事件的總線

html代碼:

<div id="app">

<a-component></a-component> <b-component></b-component>

</div>

js代碼:

var Event = new Vue();

var A = {

template:‘<div @click="clickA">A要傳參給B</div>‘,

data:function(){

return{

a:‘這裏是A傳的參數‘

}

},

methods:{

clickA:function(){

console.log(‘執行clickA...‘);

Event.$emit(‘app-click‘,this.a);

}

}

};

var B = {

template:‘<div>{{a}}</div>‘

,

data:function(){

return{

a:‘--‘

}

},

mounted:function(){

console.log(‘mounted 鉤子執行...‘);

console.log(this.number);

Event.$on(‘app-click‘,function(a){

console.log(‘監聽app-click...‘);

this.a= a;

}.bind(this));

}

};

var app = new Vue({

el:‘#app‘,

components:{

‘a-component‘: A,

‘b-component‘: B

}

});

vue非父子組件通信