Vue学习笔记(十):全局事件总线

之前博客中介绍了prop和调用事件的方式在父-子组件之间进行数据,这种方式在只有一层嵌套层时可以使用,但是路过存在多层嵌套,多层多个"兄弟"组件之间传递数据,就非常麻烦。对此,vue中提供了一种全局事件总线机制,数据传递是通过一个空的Vue实例作为中央事件总线,通过它来触发事件和监听事件,可以实现几乎任何组件间的通信,这在一些比较小的项目中是非常好用的。
全局事件总线相当于一个公共空间,任何组件都可以将事件绑定到其中,任何其他组件都可以去出发绑定到这个公共空间的方法,实现组件之间的数据交互。
使用全局事件总线之前,需要在main.js中进行安装:

复制代码
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
    el:'#app',
    render: h => h(App),
    beforeCreate() {
    	Vue.prototype.$bus = this //安装全局事件总线
    },
})

组件将事件绑定到全局事件总线中:

复制代码
<template>
    <div class="demo2">
        <hello1 
        v-for="per in persons"
        :key="per.id"
        :perObj=per
        >
        </hello1>
    </div>
</template>

<script>
import hello1 from './hello1.vue'
    export default {
        name: 'hello2',
        data(){
            return {
                persons: [
                    { id: 1, name: '张三', age: 23 },
                    { id: 2, name: '李四', age: 34 },
                    { id: 3, name: '王五', age: 45 }
                ]
            }
        },
        components:{
            hello1
        },
        mounted() {
            this.$bus.$on('changeAge1', (id)=>{   // 将事件changeAge1添加到事件总线中
                this.persons.forEach((per)=>{
                    if(per.id === id) per.age += 1
                });
                console.log('id值为:', id, 'age值加1')
            })
        }
    }
</script>

其他组件触发事件总线中的事件,实现数据交互:

复制代码
<template>
    <div class="demo1">
        <h4>{{perObj.name}} 的年龄是:{{perObj.age}}</h4>
        <!-- 此处调用从父组件中传过来的函数 -->
        <button @click="changeAge2(perObj.id)">修改年龄</button>
    </div>
</template>

<script>
    export default {
        name: 'hello1',
        props:['perObj'],
        methods: {
            changeAge2(id){
                this.$bus.$emit('changeAge1', id)
            }
        },
    }
</script>
相关推荐
an__ya__1 分钟前
Vue数据响应式reactive
前端·javascript·vue.js
苦逼的搬砖工4 分钟前
Flutter UI Components:闲来无事,设计整理了这几年来使用的UI组件库
前端·flutter
想买Rolex和Supra的凯美瑞车主6 分钟前
Taro + Vite 开发中 fs.allow 配置问题分析与解决
前端
ruanCat7 分钟前
使用 vite 的 base 命令行参数来解决项目部署在 github page 的路径问题
前端·github
Codebee12 分钟前
使用Qoder 改造前端UI/UE升级改造实践:从传统界面到现代化体验的华丽蜕变
前端·人工智能
叫我詹躲躲16 分钟前
开发提速?Vue3模板隐藏技巧来了
前端·vue.js·ai编程
华仔啊16 分钟前
面试都被问懵了?CSS 的 flex:1 和 flex:auto 真不是一回事!90%的人都搞错了
前端·javascript
前端康师傅18 分钟前
JavaScript 函数详解
前端·javascript
金金金__21 分钟前
antd v5 support React is 16 ~ 18. see https://u.ant.design/v5-for-19 for...
前端
会豪22 分钟前
工业仿真(simulation)--前端(二)-资源管理器
前端