兄弟组件间通信通过事件中心的概念进行相关通信

1、创建事件中心
var hub = new Vue()
2、监听事件和销毁事件
hub.$on('eventName',functionEvent);
hub.$off('eventName');
3、触发事件
hub.$emit('eventName');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<title>兄弟组件相互通信</title>
</head>
<body>
<div id="app">
<button-a></button-a>
<button-b></button-b>
<button-c></button-c>
</div>
</body>
<script>
var hub = new Vue();
Vue.component('button-a', {
data: function() {
return {
name: '组件A: ',
count: 0
}
},
template: '<div><div style="cursor: pointer;" @click="handle">{{name}} {{count}}</div> <div> . </div> </div>',
methods: {
handle: function() {
hub.$emit('component-b', 2);
}
},
mounted: function() {
hub.$on('component-a', (value) => {
this.count += value;
});
}
});
Vue.component('button-b', {
data: function() {
return {
name: '组件B:',
count: 0
}
},
template: '<div> <div style="cursor: pointer;" @click="handle">{{name}} {{count}}</div> </div>',
methods: {
handle: function() {
hub.$emit('component-a', 2);
}
},
mounted: function() {
hub.$on('component-b', (value) => {
this.count += value;
});
}
});
Vue.component('button-c', {
data: function() {
},
template: '<div> <input type="button" @click="deleteEvent" value="事件销毁" /> <div>',
methods: {
deleteEvent() {
hub.$off('component-a');
hub.$off('component-b');
alert("事件销毁成功!")
}
}
})
var vm = new Vue({
el: '#app',
data: {
},
methods: {
}
})
</script>
</html>
<style>
</style>
效果图如下所示:(点击A组件B组件进行响应)
