Vue全局事件总线

添加$bus属性

首先在Vue的prototype原型对象上添加$bus属性,属性的值为当前的Vue对象,作为全局事件调度器,这里我们在beforeCreate钩子函数中添加

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this
  }
}).$mount('#app')

发送事件

下面是定义了一个test事件,进行测试,最后也不要忘了在组件销毁的时候注销事件

<template>
  <div>
    <HelloWorld ref="hello" @test="getMessage"/>
    <button @click="send">发送</button>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    HelloWorld
  },
  mounted(){
    this.$bus.$on("test",this.getMessage)
  },
  methods:{
      getMessage(msg){
          alert(msg)
      },
      send(){
          this.$bus.$emit("test","全局事件")
      }
  },
  beforeDestroy() {
    this.$bus.$off("test")
  }
}
</script>

<style>

</style>

效果如下


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容