🔹🔹🔹 vue 通信方式 eventBus

没啥关系的两个组件,

找破天,都找不到啥关系的两个组件。

数据占比比较多,事件的话还要监听:

用vuex、用localstorage。


事件占比比较多

eventBus

一、使用方法:

1、在main.js中创建一个空的vue实例作为全局事件总线,同时,将其绑定在vue原型上。

js 复制代码
//main.js
Vue.prototype.$eventBus = new Vue()

2、子组件或兄弟组件,通过$emit来触发事件。

js 复制代码
sendFunc(){
    this.$eventBus.$emit( 'changeFunc' ,  123, 'abc' )
}

3、父组件或兄弟组件,通过$on来监听事件。

js 复制代码
created(){
    //绑定前需先解绑,避免反复触发、内存泄漏的问题
    this.$eventBus.$off( 'changeFunc' );  
    this.$eventBus.$on( 'changeFunc' , (val1, val2)=>{
        this.msg = val1;
        this.msg2 = val2;
    } )
}

组件监听eventBus中的事件前,一定要记得先解绑。

js 复制代码
created(){
    //this.$eventBus.$off( 'changeFunc' );  
    this.$eventBus.$on( 'changeFunc' , (val)=>{
        this.msg = val;
    } )
}

如上,绑定前不解绑的话,主要有两方面的问题:1、事件反复触发;2、内存泄漏;


很显然,上面是vue2的写法。

什么年代了还在vue2,

下面是vue3的写法:


Vue2 里常用:

js 复制代码
// eventBus.js
import Vue from 'vue'
export const eventBus = new Vue()

// 组件A
eventBus.$emit('sayHello', '你好')

// 组件B
eventBus.$on('sayHello', (msg) => {
  console.log(msg) // 你好
})

那么vue3呢,vue3没有new Vue()了啊。

vue3

  1. vue3 用 mitt
js 复制代码
npm i mitt
  1. 新建 eventBus.js
js 复制代码
// eventBus.js
import mitt from 'mitt'

// 创建一个全局事件总线
const eventBus = mitt()

export default eventBus
  1. 组件A(发送事件)
vue 复制代码
<script setup>
import eventBus from '@/eventBus.js'

function sendMessage() {
  eventBus.emit('sayHello', '你好,我是组件A')
}
</script>

<template>
  <button @click="sendMessage">发送消息</button>
</template>
  1. 组件B(接收事件)
vue 复制代码
<script setup>
import { onMounted, onUnmounted } from 'vue'
import eventBus from '@/eventBus.js'

function handleMessage(msg) {
  console.log('组件B收到消息:', msg)
}

onMounted(() => {
  eventBus.on('sayHello', handleMessage)
})

onUnmounted(() => {
  eventBus.off('sayHello', handleMessage) // 记得销毁,避免内存泄漏
})
</script>

<template>
  <div>我是组件B</div>
</template>

  • 父子组件通信:props / emits
  • 跨层级组件通信:provide / inject
  • 全局状态管理:Pinia(推荐)
  • 非父子组件通信(解耦):eventBus(基于 mitt)

完事了。

相关推荐
0思必得017 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice19 分钟前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶36020 分钟前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额1 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a3 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌413 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡4 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone4 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09014 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农4 小时前
Vue 2.3
前端·javascript·vue.js