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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
2019-02-11 配置数据字典&异步查询客户