Vue:(二十九)全局事件总线

38 篇文章 2 订阅

今天的学习内容是事件总线,什么是事件总线呢?

  1. 一种组件间通信的方式,适用于任意组件间通信

  1. 安装全局事件总线:

### main.js
new Vue({
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this // 安装全局事件总线
  },
}).$mount('#app')
  1. 使用事件总线:

  1. 接收数据:A组件想接收数据,则在A组件中的$bus绑定自定义事件,事件的回调留在A组件本身

mounted() {
  this.$bus.$on('hello', (data) => {
    console.log('我是School,收到了数据:', data)
  })
},
sendStudentName() {
  this.$bus.$emit('hello', this.name)
},
  1. 提供数据:this.$bus.$emit('xxx',数据)

  1. 最好在beforeDestory钩子中,用$off去解绑当前组件所用到的事件

### School.vue
<template>
  <div class="school">
    <h1>学校名称:{{name}}</h1>
    <h1>学校地址:{{address}}</h1>
  </div>
</template>

<script>
  export default {
    name: 'SchoolVue',
    data() {
      return {
        name: '西航',
        address: '西安',
      }
    },
    mounted() {
      this.$bus.$on('hello', (data) => {
        console.log('我是School,收到了数据:', data)
      })
    },
    beforeDestroy() {
      this.$bus.$off('hello')
    },
  }
</script>

<style>
  .school {
    background-color: blue;
    padding: 5px;
    margin-top: 30px;
  }
</style>
### Student.vue
<template>
  <div class="student">
    <h1>学生姓名:{{ name }}</h1>
    <h1>年龄:{{ age }}</h1>
    <button @click="sendStudentName">点我发送数据</button>
  </div>
</template>

<script>
  export default {
    name: 'StudentVue',
    data() {
      return {
        name: '空谷有来人',
        age: 19,
      }
    },
    methods: {
      sendStudentName() {
        this.$bus.$emit('hello', this.name)
      },
    },
  }
</script>

<style>
  .student {
    background-color: green;
    padding: 5px;
    margin-top: 30px;
  }
</style>

简单了解一下,东西虽少,但是功能强大。

我是空谷有来人,谢谢大家支持!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值