Vue全局事件总线

2022-07-06  本文已影响0人  itfitness

添加$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>

效果如下


上一篇 下一篇

猜你喜欢

热点阅读