Vue 全局事件总线

全局事件总线

事件总线其实就是vm或vc. 可以在任意组件之间通信。
具体实现是在beforeCreate里面将vm挂到Vue.prototype上去,因为VueComponent.prototype.proto === Vue.prototype
在组件的beforeDestory中要把事件总线订阅的事件解绑

案例

注册事件总线

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

// 关闭Vue的生产提示
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  beforeCreate() {
    // 注册事件总线
    Vue.prototype.$eventbus = this
  }
}).$mount('#app')

App.vue

<script>
export default {
  name: "App",
  components: { Child },
  created() {
    this.$eventbus.$on("toogleTodo", (index) => {
      this.toogleTodo(index);
    });
  },
  beforeDestroy(){
    this.$eventbus.$off("toogleTodo")
  }
};
</script>

Child.vue

<template>
  <li class="item">
      <input type="checkbox"  :checked="item.done" @click="toggleTask" />{{ item.title }}</li>
</template>

<script>
export default {
  props: ["item","index"],
  methods:{
      toggleTask(){
          this.$eventbus.$emit('toogleTodo',this.index)
      }
  }
};
</script>
posted @ 2022-02-11 20:42  IslandZzzz  阅读(186)  评论(0编辑  收藏  举报