vue3 父子组件间的通信

这篇博客详细介绍了在Vue中如何进行父子组件间的通信。首先展示了父组件如何通过props将数据传递给子组件,然后讲解了子组件如何通过事件emit将信息回调给父组件。例子中包含了具体的模板语法和脚本设置,对于理解Vue组件间通信非常有帮助。

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

父组件向子组件通信

  1. 父组件的内容
<template>
  <div class="container">
    <childComponent :msg="msg"></childComponent>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import childComponent from '../components/childComponent.vue'

const msg = ref("父组件传给子组件的值");

</script>

  1. 子组件的内容
<template>
  <div class="container">
    <div>{{ msgValue }}</div>
  </div>
</template>

<script setup>
import { ref } from "vue"

const msgValue = ref(null)
const props = defineProps({
  msg: {
    type: String,
    default: ""
  }
})
msgValue.value = props.msg

</script>

子组件向父组件通信

  1. 父组件的内容
<template>
  <div class="container">
    <span>{{ childVlaue }}</span>
    <childComponent @myClick="onMyClick"></childComponent>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import childComponent from '../components/childComponent.vue'

const childVlaue = ref(null)

const onMyClick = (val) => {
  childVlaue.value = val
}

</script>

  1. 子组件的内容
<template>
  <div class="container">
    <el-button type="primary" size="default" @click="handleClick">子组件向父组件通信</el-button>
  </div>
</template>

<script setup>

const emit = defineEmits(["handleClick"]);
const handleClick = () => {
  // 触发父组件中的方法,并把值以参数的形式传过去
  // 这里触发的方法名要和父组件中@符后面的名称一样
  emit("myClick", "子组件向父组件传送的信息");
}

</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值