初识vue 2.0(6):兄弟组件通信
如果不想引入vuex,也可以通过实例化一个vue实例(EventBus)作为媒介来进行兄弟组件通信。
在相互通信的兄弟组件之中都引入EventBus,然后通过分别调用EventBus事件的触发和监听来实现通信和参数传递。
首先,我们需要创建一个容器,去充当EventBus,创建一个utils/bus.js文件:
import Vue from 'vue' export default new Vue()
然后,创建一个父组件Game.vue,包含3个兄弟子组件,我们要做的,就是3个子组件之间的通信。
<template> <div class="game"> <h2>{{ msg }}</h2> <ul> <li><CF /></li> <li><DNF /></li> <li><LOL /></li> </ul> </div> </template> <script> import CF from './game/CF' import DNF from './game/DNF' import LOL from './game/LOL' export default { name: 'game', components: { CF, DNF, LOL, }, data () { return { msg: '我是game模块' } } } </script>
创建发送消息组件game/DNF.vue:
<template> <div class="dnf" @click="send"> <h2>{{ msg }}</h2> </div> </template> <script> import Bus from '../../utils/bus.js' export default { name: 'DNF', data () { return { msg: '我是DNF模块' } }, methods:{ send(){ Bus.$emit('on', ':(收到了来自DNF模块的消息)'); } } } </script>
创建接收消息组件game/CF.vue:
<template> <div class="cf"> <h2>{{ msg }}</h2> </div> </template> <script> import Bus from '../../utils/bus.js' export default { name: 'CF', data () { return { msg: '我是CF模块' } }, mounted() { Bus.$on('on', (msg) => { this.msg += msg; }) } } </script>
创建第二个接收消息组件game/LOL.vue:
<template> <div class="lol"> <h2>{{ msg }}</h2> </div> </template> <script> import Bus from '../../utils/bus.js' export default { name: 'LOL', data () { return { msg: '我是LOL模块' } }, mounted() { Bus.$once('on', this.get); }, methods:{ get(msg){ this.msg += msg } } } </script>
点击dnf组件,lol和cf组件,都收到了:收到了来自DNF模块的消息。
PS:父子组件也可以通过这种方式通信 ^_^