安装库:cnpm install mitt
封装 eventbus.ts:
src->utils->eventbus.ts
//eventbus.ts
import mitt from 'mitt'
const emitter = mitt()
export default emitter
使用
B2.vue:
//B2.vue
<template>
<div class="aa">
<p>子组件B</p>
<input v-model="info.name"><br>
<input v-model="info.age"><br>
<el-button type="primary" @click="emitB">派发一个事件</el-button>
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import emitter from '../utils/eventbus';
type tinfo = {
name: string,
age: number
}
const info = ref<tinfo>({ name: 'yyx', age: 12 })
const emitB = () => {
emitter.emit('on-click', info.value)
}
</script>
<style scoped lang='scss'>
div {
width: 400px;
min-height: 300px;
text-align: center;
border: 1px solid #ccc;
position: relative;
}
</style>
parent.vue:
//parent.vue
<template>
<div>
<p>这是父级</p>
<span>==================================</span>
<B2></B2>
<C2 :info="_info"></C2>
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
import emitter from '../utils/eventbus';
import B2 from '../components/B2.vue';
import C2 from '../components/C2.vue';
let _info = ref<unknown>(null)
emitter.on('on-click',(val)=>{
_info.value = val
})
</script>
<style scoped lang='scss'></style>
C2.vue:
//C2.vue
<template>
<div>组件3333333
<p>name:{{ props?.info?.name }}</p>
<p>age:{{ props?.info?.age }}</p>
</div>
</template>
<script setup lang='ts'>
type tprops = {
info?: any //有个问号?,是可选的参数,父组件在饮用的时候,可以不传
}
const props = withDefaults(defineProps<tprops>(), {
info:{
name:'张三',
age:20
}
})
</script>
<style scoped lang='scss'>
div {
width: 400px;
min-height: 300px;
text-align: center;
border: 1px solid #ccc;
}
</style>