vue3 props 如何写ts,进行类型标注

这样写:

ts 复制代码
<script setup lang="ts">
const props = defineProps({
  foo: { type: String, required: true },
  bar: Number
})

props.foo // string
props.bar // number | undefined
</script>

也可以用泛型这种写法,定义props,更直接:

ts 复制代码
<script setup lang="ts">
const props = defineProps<{
  foo: string
  bar?: number
}>()
</script>

也可以移入一个单独的接口中:

ts 复制代码
<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}

const props = defineProps<Props>()
</script>

也可以用导入文件的方式:

ts 复制代码
<script setup lang="ts">
import type { Props } from './foo'

const props = defineProps<Props>()
</script>

props 解构默认值

ts 复制代码
interface Props {
  msg?: string
  label?: string[]
}

const { msg = 'hello', labels = ['one', 'two'] } = defineProps<Props>()

版本更高后,更多用编译器宏withDefaults去做默认值。

ts 复制代码
interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two']
})
ts 复制代码
<script setup lang="ts">
interface UserProfileProps {
  userProfile: User
  showAvatar?: boolean
  avatarSize?: 'small' | 'medium' | 'large'
}

const props = withDefaults(defineProps<UserProfileProps>(), {
  showAvatar: true,
  avatarSize: 'medium'
})
</script>

withDefaults 方法是 Vue 3 中提供的一个实用工具函数,用于定义一个组件的默认属性。在创建组件时,我们可以使用 withDefaults 方法来指定默认值,这样在组件中就不需要重复定义这些默认属性了。

相关推荐
pas13614 分钟前
30-mini-vue 更新 element 的 props
前端·javascript·vue.js
魁首36 分钟前
OpenAI Codex 深入剖析:下一代 AI 编程助手的架构与原理
前端·openai·ai编程
火星数据-Tina44 分钟前
如何构建一个支持多终端同步的体育比分网站?
大数据·前端·数据库·websocket
IT_陈寒1 小时前
React 19 实战:5个新特性让你的开发效率提升50%!
前端·人工智能·后端
GuMoYu1 小时前
el-date-picker限制选择范围
前端·javascript·vue.js
冴羽1 小时前
JavaScript Date 语法要过时了!以后用这个替代!
前端·javascript·node.js
加油乐1 小时前
react使用Ant Design
前端·react.js·ant design
OEC小胖胖1 小时前
05|从 `SuspenseException` 到 `retryTimedOutBoundary`:Suspense 的 Ping 与 Retry 机制
前端·前端框架·react·开源库