1.首先安装

1
2
3
4
//npm
npm install mitt -S
//yarn
yarn add mitt -S

2.src下新建一个目录plugin,其中新建Bus.ts

1
2
3
4
5
import mitt from 'mitt'

const mitter = mitt()

export default mitter

3.A组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<script setup lang='ts'>
import { ref } from 'vue-demi'
import Bus from '../plugin/Bus'
    const str = ref('text')
    const btn = ()=>{
        Bus.emit('btn',str)
    }
</script>
           
<template>
    <div>
        A组件
        {{str}}
        <button @click="btn">按钮</button>
    </div>
</template>
           
<style scoped lang='scss'>

</style>

4.B组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup lang='ts'>
import {ref} from 'vue'
import { onBeforeMount } from 'vue-demi'
import Bus from '../plugin/Bus'
let s = ref('')
onBeforeMount(()=>{
    Bus.on('btn',(e:any)=>{
        s.value = e.value
        console.log( typeof e)
    })
})
</script>
           
<template>
    <div>
        B组件--{{s}}
    </div>
</template>
           
<style scoped lang='scss'>

</style>

记录一下。