【vue3】子传父-事件总线-mitt(子组件派发事件,父组件接收事件和传递的参数)

安装库: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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值