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>