Vue全局事件总线

作用:任意组件间通信

1、在main.js中安装全局事件总线

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

2、在需要接收数据的组件中定义自定义事件

mounted() {
    this.$bus.$on('getName', data => { // 直接写回调函数必须使用箭头函数,不然this指向有问题
      console.log('School 收到了:', data)
      this.studentName = data
    })
  },
  beforeDestroy() {
    this.$bus.$off('getName')
  }
2.1 这里的对调函数也可以写在外面,methods中,例如
methods: {
    sendMessage(data) {
      console.log('School组件收到了数据:', data)
      this.studentName = data
    }
  },
  mounted() {
    this.$bus.$on('getName', this.sendMessage)
  },
  beforeDestroy() {
    this.$bus.$off('getName') // 如果解绑多个事件可以使用 (['getName','事件名2',...])
  }

注意事项,最好在beforeDestroy钩子函数中使用$off解绑当前组件实例对象所用到的自定义事件

3、提供数据的Student组件

<template>
  <div>
    <button @click="sendName">get名字</button>
  </div>
</template>

<script>
export default {

  name: 'Student',
  data() {
    return {
      name: '张飞'
    }
  },
  methods: {
    sendName() {
      this.$bus.$emit('getName', this.name)
    }
  }
}
</script>

4、结果演示

创作不易 请尊重他人劳动成果,未经授权禁止转载!

评论

  1. 3年前
    2022-9-10 23:44:30

    Thanks for your blog, nice to read. Do not stop.

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇