在Vue 3和TypeScript中,可以使用props和emit来实现组件间的通信。以下是使用setup函数和Composition API的示例代码:
父组件传值给子组件:
// ParentComponent.vue
<template>
  <ChildComponent :parentData="parentData" />
</template>
 
<script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const parentData = ref('父组件数据');
</script>子组件接收父组件的值并进行处理:
// ChildComponent.vue
<template>
  <div>{{ parentData }}</div>
</template>
 
<script setup lang="ts">
defineProps({
  parentData: String
});
</script>子组件传值给父组件:
// ChildComponent.vue
<template>
  <button @click="sendToParent">发送给父组件</button>
</template>
 
<script setup lang="ts">
import { defineEmits } from 'vue';
 
const emit = defineEmits(['updateData']);
 
const sendToParent = () => {
  emit('updateData', '子组件数据');
};
</script>父组件监听子组件发出的事件并处理数据:
// ParentComponent.vue
<template>
  <ChildComponent @updateData="handleDataFromChild" />
</template>
 
<script setup lang="ts">
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const handleDataFromChild = (data: string) => {
  console.log(data);
};
</script>组件间传值:
// SiblingComponentA.vue
<template>
  <SiblingComponentB :dataFromA="dataFromA" />
</template>
 
<script setup lang="ts">
import { ref } from 'vue';
import SiblingComponentB from './SiblingComponentB.vue';
 
const dataFromA = ref('数据从A到B');
</script>
// SiblingComponentB.vue
<template>
  <div>{{ dataFromA }}</div>
</template>
 
<script setup lang="ts">
import { defineProps } from 'vue';
 
defineProps({
  dataFromA: String
});
</script>以上代码展示了在Vue 3和TypeScript中如何使用setup函数和Composition API进行组件间通信的基本方法。