Vue全局事件总线的配置和使用

Vue全局事件总线详解

简介:全局事件总线是一种组件间通信的方式,适用于任意组件间通信。

可以调用 $on 、 $off 和 $emit 方法,因为这三个方法在Vue原型对象上,所以我们的全局事件总线就要放在Vue的原型对象(vue.prototype)上,以确保每个组件都能访问得到。

实现:

main.js:

new Vue({
  el: '#app',
  router,
  store,
  beforeCreate() {
    Vue.prototype.$bus = this // 配置全局事件总线
  },
  render: h => h(App)
})

子组件 Student.vue

<template>
  <div class="student">
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <button @click="sendStudentName">把学生名给School组件</button>
  </div>
</template>

<script>
export default {
  name: 'Student',
  data() {
    return {
      name: '张三',
      age: '20'
    }
  },
  methods: {
    sendStudentName() {
      this.$bus.$emit('hello', this.name)
    }
  }
}
</script>

子组件 School.vue

<template>
  <div class="school">
    <h2>学校:{{ name }}</h2>
    <h2>地址:{{ address }}</h2>
  </div>
</template>

<script>
export default {
  name: 'School',
  data() {
    return {
      name: '家里蹲大学',
      address: 'home'
    }
  },
  mounted() {
    this.$bus.$on('hello', (data) => {
      console.log('我是School组件 收到了数据', data)
    })
  },
  beforeDestroy() {
    this.$bus.$off('hello') // 销毁阶段,$off解绑当前组件所用到的事件
  }
}
</script>

父页面

<template>
  <div>
    <Student />
    <School />
  </div>
</template>

<script>
import Student from './component/Student'
import School from './component/School'

export default {
  components: {
    Student,
    School
  }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值