通过bus进行组件通信

vue中组件的通信:props bus vuex …

兄弟通信

非父子组件的通信

1
2
3
// bus.js
import Vue from 'vue';
export default new Vue();
1
2
3
4
5
6
7
8
9
// b1.vue
// 触发组件 b2 中的事件
bus.$emit('id-selected', 1)

// b2.vue
// 在组件 b2 创建的钩子(created)中监听事件
bus.$on('id-selected', function (id) {
// ...
})

父子通信

自定义事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//父子通信用props,子父通信用自定义事件


<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>


Vue.component('button-counter', {
template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})

原理:通过一个空的vue对象,来监听和发送自定义事件。

还有一个办法

使用引用对象。

在复杂的情况下,我们应该考虑使用专门的状态管理模式(vuex)。