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