vue3 ts 兄弟组件传值

前言

组件和router-view之间的传值也是组件之间的传值

使用mitt

使用mitt代替vue2中兄弟组件之前的传值通信

安装

#安装命令
npm install mitt -S

全局注册

注意这里采用vue3+ts的方式使用

// 引入
import mitt from 'mitt'
//定义
type Events = {
  foo: string;
  bar: number;
};
const Mit = mitt<Events>()
//全局声明
declare module 'vue' {
    export interface ComponentCustomProperties{
        $Bus: typeof Mit
    }
}
const app = createApp(App)
app.config.globalProperties.$Bus = Mit

组件之间使用

这里使用非语法糖模式

组件1发送
import {getCurrentInstance} from "vue";

const { proxy } = getCurrentInstance() as any;

//发送

const click = () =>{
    proxy?.$Bus.emit('query',xxx需要通信的内容)
}

组件2接收
import {getCurrentInstance} from "vue";

const { proxy } = getCurrentInstance() as any;

//直接接收组件1的发送内容

proxy?.$Bus.on('query',(obj: any) =>{
    console.log('接收的值为',obj)
})

希望对你有用!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值