vue3事件总线使用

vue3本身没有直接实现事件总线的方法,在需要使用事件总线时,需要引入第三方‘mitt’。(npm i --save mitt

第一步: 创建一个event-bus.ts文件(这里也可以使用js,一样的)

代码如下:

import Mitt from 'mitt'
const eventHub = new Mitt();
export default eventHub;

 

 第二步挂载到全局,在main.ts中引入event-bus.ts文件

1 import { createApp } from 'vue'
2 import './style.css'
3 import App from './App.vue'
4 import eventHub from './util/event-bus'
5 
6 const app = createApp(App)
7 app.config.globalProperties.eventHub = eventHub;
8 app.mount('#app')

组件中使用:

创建父组件HelloWorld.vue,代码为

<template>
  <div>
    父组件
    <div style="display:flex;width: 100%;margin-top:10px">
      <!-- 子组件1 -->
      <helloworldChild1 style="width:50%;height:300px"></helloworldChild1>
      <!-- 子组件2 -->
      <helloworldChild2 style="width:50%;height:300px"></helloworldChild2>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import helloworldChild1 from "./components/helloworld-child-1.vue"
import helloworldChild2 from "./components/helloworld-child-2.vue"
//组件引用
const { eventHub } = getCurrentInstance()?.proxy;
onMounted(() => {
  //时间传参
  eventHub.emit('event-name', "你是猪")
})
</script>

<style lang="less" scoped>

</style>

创建子组件1:helloworld-child-1.vue。代码为

 1 <template>
 2 <div class="helloworld-child">
 3     子组件一{{parentData}}
 4     <button @click="fun()">我要给兄弟二传参,别拦我</button>
 5 </div>
 6 </template>
 7 
 8 <script lang="ts" setup>
 9 import { ref,getCurrentInstance,onMounted } from "vue";
10 const {eventHub} = getCurrentInstance()?.proxy;
11 const parentData = ref<any>();
12 //获取组件参数
13 const eventHandler= (res:any)=>{
14     parentData.value = '父组件参数来了:'+res;
15 }
16 const index =ref(1);
17 const fun=()=>{
18     index.value = index.value+1;
19     eventHub.emit('event-child-1',"你兄弟1传了个参"+index.value+"过来了")
20 }
21 // 组件订阅
22 eventHub.on('event-name', eventHandler);
23 </script>
24 
25 <style lang="less" scoped>
26 .helloworld-child{
27     border: 1px solid red;
28 }
29 </style>

创建子组件2:helloworld-child-2.vue。代码为

<template>
    <div class="helloworld-child">
        子组件二{{parentData}}
        <div>
            {{parentData1}}
            </div>
</div>
</template>
    
<script lang="ts" setup>
import { ref,getCurrentInstance } from "vue";
const { eventHub } = getCurrentInstance()?.proxy;
const parentData = ref<any>();
const parentData1 = ref<any>();
//获取组件参数
const eventHandler= (res:any)=>{
    parentData.value = '父组件参数来了:'+res;
}
const eventHandler1= (res:any)=>{
    parentData1.value =res;
}
// 参数订阅
eventHub.on('event-name', eventHandler);
eventHub.on('event-child-1', eventHandler1);

</script>
    
<style lang="less" scoped>
.helloworld-child {
    border: 1px solid rgb(22, 7, 237);
}
</style>

页面操作

 

posted @ 2022-09-23 11:49  奔跑的哈密瓜  阅读(1482)  评论(0编辑  收藏  举报