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 方法来指定默认值,这样在组件中就不需要重复定义这些默认属性了。

相关推荐
骇客野人8 分钟前
Java 前后端可部署落地架构方案
服务器·前端·微服务
OpenTiny社区15 分钟前
从开发到运行:OpenTiny NEXT 如何构建 Agent 时代的 Web 应用
前端·开源·ai编程·opentiny
feixing_fx20 分钟前
伪类与伪元素的魔法:纯 CSS 打造炫酷的按钮悬停特效
前端·css·css3
动恰客流统计20 分钟前
用客流数据优化门店排班:高峰不缺人、平峰不浪费的落地路径
大数据·前端·人工智能
广州山泉婚姻30 分钟前
前后端分离的核心优势
前端·后端
志尊宝30 分钟前
Vue3 零基础每日笔记(043):defineModel 与 defineExpose 的 TS 用法——3.4+ 新 API 进阶
前端·javascript·vue·html·vue3
洛兮银儿32 分钟前
前端页面引入cesium
前端·cesium
SEO_juper42 分钟前
2026年用Python分析网站访问日志:看清Googlebot和AI爬虫怎么爬你的站(附完整代码)
开发语言·前端·seo·独立站·谷歌优化
摸鱼仙人~44 分钟前
React 原理进阶:彻底理解 re-render、React.memo、useMemo 与 useCallback
前端·vue.js
IMPYLH1 小时前
HTML 的 <small> 元素
前端·网络·html