vue3 props 如何接受多个类型?

博客提到采用Vue2写法时编辑器会报错,指出Vue3变更为数组写法,体现了Vue2与Vue3在写法上的差异。

采用vue2写法,编辑器报错
在这里插入图片描述
vue3 变更为数组写法
在这里插入图片描述

Vue 3 中使用 TypeScript 时,可以通过定义接口(interface)或类型(type)来传递多个 props 值。这样可以确保组件间的数据传递具有明确的结构和类型检查。 ### 定义 Props 类型 首先,可以定义一个接口或类型来描述传递给子组件的 props: ```typescript interface ChildProps { title: string; count: number; isActive: boolean; } ``` ### 在子组件中使用 Props 在子组件中,使用 `defineProps` 函数来声明 props,并指定其类型为之前定义的接口或类型: ```vue <script setup lang="ts"> interface ChildProps { title: string; count: number; isActive: boolean; } const props = defineProps<ChildProps>(); </script> <template> <div> <h1>{{ title }}</h1> <p>Count: {{ count }}</p> <p>Active: {{ isActive ? &#39;Yes&#39; : &#39;No&#39; }}</p> </div> </template> ``` ### 在父组件中传递 Props 在父组件中,可以通过绑定对象的方式传递多个 props 值。使用 `v-bind` 或 `:` 指令来传递 props: ```vue <template> <ChildComponent :title="parentTitle" :count="parentCount" :is-active="parentIsActive" /> </template> <script setup lang="ts"> import ChildComponent from &#39;./ChildComponent.vue&#39;; const parentTitle = &#39;Hello Vue 3&#39;; const parentCount = 5; const parentIsActive = true; </script> ``` ### 使用解构传递 Props 如果希望以更简洁的方式传递 props,可以使用解构的方式将对象展开为多个 props: ```vue <template> <ChildComponent v-bind="{ title, count, isActive }" /> </template> <script setup lang="ts"> import ChildComponent from &#39;./ChildComponent.vue&#39;; const title = &#39;Hello Vue 3&#39;; const count = 5; const isActive = true; </script> ``` 通过这种方式,可以在 Vue 3 中使用 TypeScript 安全地传递多个 props 值[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

归来巨星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值