一、定义 Props 类型
首先,我们需要定义一个接口来描述我们的props类型。这通常在一个专门的类型声明文件中完成,例如types/index.ts:
二、创建父组件
父组件负责定义数据和传递props给子组件。以下是父组件Parents.vue的示例:
三、创建子组件
在子组件中,我们将演示三种不同的方法来接收父组件传递的 props。
1.只接收值 (defineProps)
在这种方法中,我们简单地接收并使用传递的值。
2. 接收并限制类型 (defineProps + 类型注释)
在这种方法中,我们通过定义类型来限制接收的 props。
3. 接收、限制类型、设置默认值 (withDefaults)
在这种方法中,我们不仅限制类型,还设置默认值,以确保在没有传递 props 时组件能正常工作。
总结
在 Vue 3 中使用 TypeScript 定义和使用 Props。我们展示了三种方法来接收和处理父组件传递的数据:>
这样,我们就创建了一个更加健壮和可维护的 Vue 3 组件系统。