V3.2 的组件通信

65 阅读1分钟
  1. 父传子
// 在子组件中需要使用 defineProps() 函数来获取props
// 不需要在前面加props 前缀也可以在插值语法中读取
<h2>{{ props.x.name }}--{{ x.age }}</h2>
<script setup>
    const props = defineProps(['name','x','y'])
    // 这里不加props 前缀就无法获取到变量
    const y = props.y
    console.log(y);
</script >

2.子传父

// 在子组件中需要使用 defineEmits() 函数来注册自定义事件
<button @click="onAdd">按钮</button>
<script setup>
                     // 注册自定义事件
    const emit = defineEmits(['onMes'])
    const onAdd = () => { 
      // 第一个参数是自定义事件名称 后面的是传递的参数
      emit('onMes','你好皮皮',[1,2,3],{q:'123'})
     }
</script >
// 子传父 在父组件中
<child  @onMes="mes"/>
<script setup>
    // val,y,z 都是子组件传递的参数
    const mes = (val,y,z) => { 
    ste.mes = val
    console.log(y);
    console.log(z);
   }
</script >

3.消息订阅与发布 兄弟传兄弟

// 新建EventBus.js 文件
// 然后引入mitt 
import mitt from "mitt"; 
// 创建实例对象并且暴露
const mitts = mitt(); 
export default mitts;
// 在组件A中 使用 emit 发送消息
<button @click="onAdd">按钮</button>
<script setup>
    // 引入mitts
    import mitts from '../EventBus'
    const onAdd = () => { 
    // 第一个参数是 发布的消息名称 第二个是消息内容
    mitts.emit('mes','发送的消息')
   }
</script >
// 在组件B中 使用 on 接收消息
<script setup>
    // 引入mitts
    import mitts from '../EventBus'
    // 此步骤也可以在生命周期函数内执行
    // 第一个参数是 事件名称 第二个参数是函数,函数的参数是接收的消息内容
    mitts.on('mes',(val) => { 
    // 赋值给变量
    test.value = val
    })

</script >