Vue3父子组件通信

在Vue 3中,父子组件之间的通信可以通过propsemit来实现。父组件通过props向子组件传递数据,子组件通过事件emit将信息发送回父组件。

父组件 (ParentComponent.vue):

<template>
  <div>
    <ChildComponent :parentData="parentData" @childEvent="handleChildEvent" />
  </div>
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentData = ref('父组件数据');
 
const handleChildEvent = (value) => {
  console.log('子组件触发的事件', value);
};
</script>

子组件 (ChildComponent.vue):

<template>
  <div>
    <p>{{ parentData }}</p>
    <button @click="sendToParent">发送到父组件</button>
  </div>
</template>
 
<script setup>
import { defineProps, defineEmits } from 'vue';
 
const props = defineProps(['parentData']);
const emit = defineEmits(['childEvent']);
 
const sendToParent = () => {
  emit('childEvent', '子组件数据');
};
</script>

在这个例子中,父组件通过:parentData="parentData"parentData作为props传递给子组件,并监听子组件触发的childEvent事件。子组件通过点击按钮触发sendToParent函数,该函数通过emit('childEvent', '子组件数据')发送数据给父组件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值