在Vue 3中,使用TypeScript进行父子组件通信的方式与使用JavaScript是类似的,只是需要注意类型的声明。defineProps
和defineEmits
是在子组件中用于声明props和emits的函数。
// ChildComponent.vue
<template>
<button @click="increment">{{ count }}</button>
</template>
<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
initialCount: {
type: Number,
required: true
}
});
const emit = defineEmits(['increment']);
let count = props.initialCount;
const increment = () => {
count++;
emit('increment', count);
};
</script>
// ParentComponent.vue
<template>
<div>
<p>Parent Count: {{ parentCount }}</p>
<ChildComponent :initialCount="parentCount" @increment="updateParentCount" />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
let parentCount = ref(0);
const updateParentCount = (count: number) => {
parentCount.value = count;
};
</script>
子组件ChildComponent
接收一个名为initialCount
的prop,它通过defineProps
声明。在父组件ParentComponent
中,将parentCount
传递给子组件作为initialCount
prop,并在子组件中的点击事件时更新父组件的状态。