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 @   IslandZzzz  阅读(193)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2019-02-11 配置数据字典&异步查询客户
点击右上角即可分享
微信分享提示