Vue3+Mitt

import mitt from 'mitt'
declare module 'vue'{
    export interface ComponentCustomProperties {
        $Bus:typeof Mitt
    }
}
const app=createApp(App)
app.config.globalProperties.$Bus = Mitt

引入并挂载到main.ts

// 使用说明:setup的执行时组件对象还没有创建,此时不能使用this来访问data/computed/methods/props
// 我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象,也就是当前vue这个实例对象
//  这个可以访问的东西有很多可以打印到控制台去看看 因为获取的是实例所以应该接近vu2里的this
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();
const passValue = (s: string) => {
  // 因为对象可能为null所以加了个?
  instance?.proxy?.$Bus.emit("onCustom", s);
};
</script>

兄弟组件一 传一个值

import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();
console.log(instance?.proxy);

instance?.proxy?.$Bus.on("onCustom", (s) => {
  console.log(s);
});

兄弟组件2可以接收

注:可选链操作符:

可选链操作符 ( ?. ) 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空 (nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。在探索一个对象的内容时,如果不能确定哪些属性必定存在,可选链操作符也是很有帮助的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值