关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

vue3 语法糖setup 兄弟组件传值

发布时间:2023-06-29 19:00:40

使用 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组件传值


/template/Home/leiyu/PC/Static