Vue3--父子组件通信(父传子、子传父)详细代码

本文介绍了在Vue应用中创建一个简单的父子组件结构,通过`ref`在父组件传递数据到子组件,以及如何在子组件中通过`props`接收并显示父组件的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父传子

父组件 FatherComponent.vue

父组件中有一个parentData 值为 ‘父组件数据’

<!-- 父组件 -->
<template>
  <div>

  </div>
</template>
 
<script setup>
import { ref } from 'vue';
const parentData = ref('父组件数据');
</script>

子组件 ChildComponent.vue

想要在子组件中显示父组件的 parentData 

<!-- 子组件 -->
<template>
  <div>我是子组件,这是父组件的值:</div>
</template>
 
<script setup>

</script>

首先将子组件引入父组件,这是父组件中就会显示子组件里的内容

<!-- 父组件 -->
<template>
  <ChildComponent />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentData = ref('父组件数据');
</script>

 然后在父组件中设置传递子组件的参数,在<ChildComponent  />子组件标签中用冒号绑定一个值,:parentData 是子组件接收数据的变量名,等号后面的 parentData 是父组件的参数

<!-- 父组件 -->
<template>
  <ChildComponent :parentData="parentData" />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentData = ref('父组件数据');
</script>

父组件要做的已经完成,下面看子组件,目前父组件已经将 const parentData = ref('父组件数据');

这一变量传递给了子组件,现在需要子组件进行接收

使用 defineProps 进行接收,接受方法如下:

<!-- 子组件 -->
<template>
  <div>我是子组件,这是父组件的值:{{ parentData }}</div>
</template>
 
<script setup>
import { defineProps } from 'vue';
 
const props = defineProps({
  parentData: String
});
</script>

这样就是父组件向子组件传递参数的方法

子传父

子传父需要用到 defineEmits 去向父组件传参,使用方法如下:

首先子组件需要使用 defineEmits ,并且填写要传递的子组件参数

<!-- 子组件 -->
<template>
  <div>我是子组件</div>
</template>
 
<script setup>
import { defineEmits } from 'vue';
const value = '子组件参数'
const childEmit = defineEmits(["childValue"]);
//使用childEmit传递参数
childEmit('childValue',value )
</script>

然后父组件需要接收子组件的参数,通过@来绑定一个函数即可,函数的回调就是子组件的参数

需要注意的是父组件@所绑定的方法要与子组件一致

<!-- 父组件 -->
<template>
  <ChildComponent @childValue="getChild" />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const getChild = (val)=>{
    console.log('接收的子组件参数:',val)
}
</script>

以上就是父子组件传参的方法

ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值