兄弟间通信bus.js

兄弟间通信:

场景:点击子组件一更改子组件二的内容

bus.js:

import Vue from 'vue'
export default new Vue;

父组件:

<template>
  <div id="app">
    <my-page />
    <my-page-two />
  </div>
</template>

<script>
import myPage from './components/myPage.vue'
import myPageTwo from './components/myPage1.vue'
export default {
  components: {
    myPage,
    myPageTwo
  }
}
</script>

子组件一 myPage.vue:

<template>
  <div class="title-div" @click="changeEvent">111</div>
</template>

<script>
import bus from './bus'
export default {
  name: 'MyPage',
  data () {
    return {}
  },
  methods: {
      changeEvent() {
          bus.$emit('text', 'ABCCD')
      }
  }
}
</script>
<style scoped>
    .title-div {
        width: 100%;
        height: 100px;
        background: yellow;
    }
</style>

子组件二 myPage1.vue:

<template>
  <div class="title-div">{{mag}}</div>
</template>

<script>
import bus from './bus'
export default {
  name: 'MyPage',
  data () {
    return {
      mag: '222'
    }
  },
  mounted() {
    bus.$on('text', val => {
      this.mag = val
    })
  }
}
</script>
<style scoped>
    .title-div {
        width: 100%;
        height: 100px;
        background: red;
    }
</style>

注意:需要通信的子组件要引入同一个bus.js,使用bus.$emit()发送消息,使用bus.$on()监听。

 

运行结果:(点击黄色区域更新红色区域文字)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值