首页 > 其他分享 >vue3探索——组件通信之事件总线

vue3探索——组件通信之事件总线

时间:2023-08-19 14:44:39浏览次数:34  
标签:vue const bus mitt 总线 vue3 组件 import emitter

Vue2.x使用EventBus进行组件通信,而Vue3.x推荐使用mitt.js

比起Vue实例上的EventBusmitt.js好在哪里呢?首先它足够小,仅有200bytes,其次支持全部事件的监听和批量移除,它还不依赖Vue实例,所以可以跨框架使用,React或者Vue,甚至jQuery项目都能使用同一套库。

安装

  • 使用yarn安装
yarn add mitt
  • 或者通过npm安装
npm install --save mitt

官方使用案例

import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

示例

  • 可以封装一个ES模块,对外暴露一个mitt实例
// src/common/bus.js

// 引入mitt插件
import mitt from 'mitt';
const $bus = mitt();
export default $bus;
  • 挂载到Vue全局变量上
// src/main.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

import $bus from './bus/index.ts'

const app = createApp(App);
app.config.globalProperties.$bus = $bus;

app.mount('#app');
  • 在父组件中使用
// src/App.vue

<template>
  <div>
    <button @click="giveMoney(200)">打钱</button>
    <Son></Son>
  </div>
</template>

<script lang="ts" setup>
import Son from './components/son.vue';
import { getCurrentInstance } from 'vue';

const { proxy }: any = getCurrentInstance();
const $bus = proxy.$bus;

function giveMoney(num: number) {
	// 通过emit方法触发
  $bus.emit('add', num);
}
</script>
  • 在子组件中使用
// src/components/son.vue

<template>
    <div>
        <h2>I am son</h2>
        <p>我收到了{{ money || 0 }}¥</p>
    </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue';

const { proxy }: any = getCurrentInstance();
const $bus = proxy.$bus;

const money = ref(0);

// 通过on方法监听
$bus.on('add', (number: number) => {
    // console.log(number);
    money.value = number;
});
</script>
  • 移除事件
// src/App.vue

<button @click="$bus.off('add')">卸载bus总线</button>
<button @click="$bus.all.clear()">卸载所有bus总线</button>

标签:vue,const,bus,mitt,总线,vue3,组件,import,emitter
From: https://www.cnblogs.com/cry0-0/p/17642450.html

相关文章

  • vue数据传递【父子组件】-父子props,子父$emit
    一、父子组件传递1、父组件数据传递给子组件【props】父组件的数据变化时,子组件会自动更新在父组件中引用子组件<子组件name/>import子组件from./子组件位置/子组件所在vue.vue在组件中注册子组件components:{子组件名称}子组件可以通过props选项声明接收该prop......
  • vue3 vite后台管理模板项目打包报错 Some chunks are larger than 500 KiB after mini
    ​ 1、错误原因分析:超过块大小限制,块大小默认500KB2、解决办法:在vite.config.js中增加output配置项build:{chunkSizeWarningLimit:1500,//调整包的大小rollupOptions:{output:{//最小化拆分包manualChunks(id){......
  • vue3常见的难点
    vue中params和query的区别,以及具体用法:https://blog.csdn.net/weixin_42282727/article/details/107505014route、router区别:https://blog.csdn.net/m0_67948827/article/details/127051410......
  • java实现大文件上传组件
    ​ 文件上传下载,与传统的方式不同,这里能够上传和下载10G以上的文件。而且支持断点续传。通常情况下,我们在网站上面下载的时候都是单个文件下载,但是在实际的业务场景中,我们经常会遇到客户需要批量下载的场景,还有文件夹的下载场景。与传统业务需求相比,新的业务需求要求更高,难度也......
  • \\NSHA10320UAP.ubsglobal-prod.msad.ubs.net\d$\data\部署包\组件全量0818\组
    com.yss.ams.bbzx-202308031009-V2.0.0.10.39-20221115.jarcom.yss.ams.reportConfigSetting-20230714135143.jarcom.yss.ams.ReportViewer-202308031009-V2.0.0.10.39-20221115.jarcom.yss.ams.website-202308031009-V2.0.0.10.39-20221115.jarcom.yss.sofa.foundation.autho......
  • vue3新语法糖——setup script
    vue3新语法糖——setupscriptCoCoyY12021-03-2712:5241480 前言vue3上线已经很久了,许多小伙伴应该都已经使用过vue3了。那么在使用vue3compositionAPI的时候有没有觉得整个过程会比较繁琐呢。比如当你定义了一个方法,然后发现模板需要使用该方法,然后就必须将方法返回......
  • wpf 自定义轮播图组件
      轮播图组件代码:[Localizability(LocalizationCategory.None,Readability=Readability.Unreadable)][TemplatePart(Name="Part_Grid",Type=typeof(Grid))][TemplatePart(Name="Part_OldContentControl",Type=typeof(ContentControl))][Template......
  • vue2公共组件=》筛选条件
    源码<template><divclass="c__filter":style="`height:${showFilter?'auto':'47px'}`"v-if="filterNum>0"ref="tableFilter"><divclass="c_filte......
  • 谈谈Vue3中的ref和reactive
    一、是什么?ref和reactive是Vue3中用来实现数据响应式的API一般情况下,ref定义基本数据类型,reactive定义引用数据类型(我喜欢用它来定义对象,不用它定义数组,原因后面讲)我理解的ref本质上是reactive的再封装二、先聊reactivereactive定义引用数据类型(以对象和数组举例),它能够将复......
  • vue-treeselect 树下拉组件被遮挡问题
    vue-treeselect组件官方中文网站: https://www.vue-treeselect.cn/需求背景:在el-tabs内容中添加此组件出现被遮挡问题通过文档查询解决方法<treeselectv-model="params.wardIds":options="hospitalWardTree"value-consists-of="LEAF_PRIORITY"placeholder=......