vue2.0中兄弟组件间的通讯是通过eventBus(事件发布订阅)实现的。
eventBus.js
import Vue from 'vue' const eventBus = new Vue() export default eventBus
父组件brother.vue
<template> <div> <bro1></bro1> <bro2></bro2> </div> </template> <script> import bro1 from '../../components/br1' import bro2 from '../../components/br2' export default{ components: { bro1, bro2 } } </script>
子组件1
bro1.vue
<template> <div> <span>this is big bro</span> <input type="text" v-model="bro1"> <button @click="sendMsg">click to send to bro2</button> </div> </template> <script> import eventBus from '../eventBus.js' export default{ data () { return { bro1: '' } }, methods: { sendMsg () { //在bro1中触发 eventBus.$emit('bad-man-comes', this.bro1) } } } </script>
子组件2
bro2.vue
<template> <div> <span>this is little bro</span> <input type="text" v-model="bro2"> </div> </template> <script> import eventBus from '../eventBus' export default{ data () { return { bro2: '' } }, mounted () { eventBus.$on('bad-man-comes', (params) => { // 在bro2中监听 this.bro2 = params }) } } </script>