使用 mitt
// 全局引入 npm install mitt 或者 cnpm install mitt • 1 • 2 • 3 • 4
在main文件中挂载
import { createApp } from 'vue' import App from './App.vue' import mitt from 'mitt' // 导入mitt const app = createApp(App) app.config.globalProperties.$mitt = new mitt() // mitt在vue3中挂载到全局 app.mount('#app') • 1 • 2 • 3 • 4 • 5 • 6 • 7
组件1 借助imtt 通过emit传值
import { defineComponent,ref,reactive,getCurrentInstance } from 'vue' // 兄弟组件传值 let { proxy } = getCurrentInstance() let brother = ref(100) function sendBrotherData() { // 通过暴露info 传递 brother 的值 proxy.$mitt.emit('info', brother.value) } " _ue_custom_node_="true">• 1 • 2 • 3 • 4 • 5 • 6 • 7 • 8 • 9 • 10
组件2
import { defineComponent,ref,reactive,getCurrentInstance } from 'vue' let { proxy } = getCurrentInstance() // 拿到info,获取info内部的值 proxy.$mitt.on('info', (res) => { console.log(res) // 打印 100 }) " _ue_custom_node_="true">• 1 • 2 • 3 • 4 • 5 • 6 • 7 • 8 • 9 • 10
关于父子组件传值的内容请看另一篇:vue3语法糖+ts组件传值
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者