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>

vue中兄弟组件间通讯

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-02-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-05-22
  • 2021-07-12
  • 2021-07-08
  • 2022-12-23
相关资源
相似解决方案