基本原理
通过事件中心管理兄弟组件
- 单独的事件中心管理组件间的通信
let eventHub = new Vue();
- 事件监听与事件销毁
//第一个参数是自定义事件的名称,第二个参数是事件函数
eventHub.$on('add-todo', addTodo);
//事件销毁
eventHub.$off('add-todo')
- 触发事件
//第一个参数是自定义事件的名称,第二个参数是携带的参数
eventHub.$emit('add-todo', id)
示例
html:
<div id='app'>
<test-tom></test-tom>
<test-jerry></test-jerry>
<button @click='destroyEvent'>销毁</button>
</div>
js:
//创建事件中心
let hub = new Vue();
Vue.component('test-tom', {
data: function(){
return{
num: 0
}
},
template: `
<div>
<div>Tom:{{num}}</div>
<button @click='handle'>点击</button>
</div>
`,
methods: {
handle: function() {
//触发兄弟组件的事件
hub.$emit('jerry-event', 2)
}
},
mounted: function() {
//监听事件
hub.$on('tom-event', (val) => {
this.num += val;
})
}
})
Vue.component('test-jerry', {
data: function(){
return{
num: 0
}
},
template: `
<div>
<div>Jerry:{{num}}</div>
<button @click='handle'>点击</button>
</div>
`,
methods: {
handle: function() {
//触发兄弟组件的事件
hub.$emit('tom-event', 1)
}
},
mounted: function() {
//监听事件
hub.$on('jerry-event', (val) => {
this.num += val;
})
}
})
var vm = new Vue({
el: '#app',
data: {
},
methods: {
destroyEvent: function(){
//销毁
hub.$off('tom-event');
hub.$off('jerry-event');
}
}
})