vue3+ts父组件向子组件传值
时间: 2025-05-24 20:33:17 浏览: 13
### 实现 Vue 3 和 TypeScript 中父组件向子组件传递值
在 Vue 3 结合 TypeScript 开发时,通过 `props` 可以方便地从父组件向子组件传递数据。下面展示了一个具体的例子来说明这一过程。
#### 定义子组件接收属性
子组件需先定义好可以接受哪些来自父级的数据项作为其自身的 prop 属性,在 `<script setup>` 或者选项 API 下都可以完成此操作:
```typescript
// 子组件 ChildComponent.vue
<script lang="ts" setup>
import { defineProps } from 'vue';
interface Props {
title?: string;
}
const props = withDefaults(defineProps<Props>(), {
title: 'Default Title'
});
</script>
<template>
<div>{{ title }}</div>
</template>
```
这段代码展示了如何利用接口定义 Prop 类型并设置默认值[^1]。
#### 父组件传递属性给子组件
接着是在父组件里指定要发送的信息以及目标子组件的位置:
```html
<!-- 父组件 ParentComponent.vue -->
<template>
<ChildComponent :title="'Customized Title'" />
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import ChildComponent from './components/ChildComponent.vue';
export default defineComponent({
name: 'ParentComponent',
components: {
ChildComponent,
},
});
</script>
```
这里演示了怎样把字符串 `'Customized Title'` 作为一个名为 `title` 的 prop 发送给子组件实例。
上述方法不仅限于基本类型的传输;对于更复杂的结构化数据(比如对象),同样适用相同的模式来进行传递和处理[^3]。
阅读全文
相关推荐

















