父组件
<template>
<view>
<ChildComponent :childMsg="parentMsg" @updateParentMsg="handleUpdateParentMsg" />
<view>父组件接收到的消息: {{ parentReceivedMsg }}</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentMsg = ref('这是来自父组件的消息');
const parentReceivedMsg = ref('');
function handleUpdateParentMsg(msg: string) {
parentReceivedMsg.value = msg;
}
</script>
子组件
<template>
<view @click="sendToParent">点击我传值给父组件</view>
<view>子组件接收到的消息: {{ childMsg }}</view>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps<{
childMsg: string;
}>();
// 使用计算属性为 childMsg 提供一个默认值
const childMsgWithDefault = computed(() => props.childMsg ?? '默认消息');
// 官方文档 withDefaults
/* const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
}) */
const emit = defineEmits(['updateParentMsg']);
function sendToParent() {
const childMsgToSend = '这是来自子组件的消息';
emit('updateParentMsg', childMsgToSend);
}
</script>