Vue父子组件之间的数据传递

1. 父组件向子组件传递数据(props

<!-- 父组件 ParentComponent.vue -->
<template>
  <div>
    <h1>我是父组件</h1>
    <!-- 使用props向子组件传递数据 -->
    <ChildComponent :message="parentMessage" />
  </div>
</template>

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

const parentMessage = ref('Hello from Parent');
</script>
<!-- 子组件 ChildComponent.vue -->
<template>
  <div>
    <h2>我是子组件</h2>
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
import { toRefs } from 'vue';

const props = defineProps({
  message: String
});

// 使用 `toRefs` 将 `props` 转换为响应式
const { message } = toRefs(props);
</script>

2. 子组件向父组件传递数据(emit

<!-- 父组件 ParentComponent.vue -->
<template>
  <div>
    <h1>我是父组件</h1>
    <ChildComponent @update-message="handleUpdateMessage" />
    <p>从子组件接收到的消息:{{ receivedMessage }}</p>
  </div>
</template>

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

const receivedMessage = ref('');

function handleUpdateMessage(newMessage) {
  receivedMessage.value = newMessage;
}
</script>
<!-- 子组件 ChildComponent.vue -->
<template>
  <div>
    <h2>我是子组件</h2>
    <button @click="sendMessage">发送消息给父组件</button>
  </div>
</template>

<script setup>
const emit = defineEmits(['update-message']);

function sendMessage() {
  emit('update-message', 'Hello from Child');
}
</script>

3. 使用 ref 直接访问子组件实例

<!-- 父组件 ParentComponent.vue -->
<template>
  <div>
    <h1>我是父组件</h1>
    <ChildComponent ref="childRef" />
    <button @click="callChildMethod">调用子组件方法</button>
  </div>
</template>

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

const childRef = ref(null);

function callChildMethod() {
  if (childRef.value) {
    childRef.value.childMethod();
  }
}
</script>
<!-- 子组件 ChildComponent.vue -->
<template>
  <div>
    <h2>我是子组件</h2>
  </div>
</template>

<script setup>
import { ref } from 'vue';

function childMethod() {
  console.log('子组件方法被调用');
}

// 使用 `defineExpose` 公开方法
defineExpose({
  childMethod
});
</script>

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值