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

相关推荐
Anlici20 小时前
连载小说大学生课设 需求&架构
前端·javascript·后端
2501_9387699921 小时前
React Server Components 进阶:数据预取与缓存
前端·react.js·缓存
蒜香拿铁1 天前
Angular【基础语法】
前端·javascript·angular.js
xiaoxiao无脸男1 天前
纯css:一个好玩的按钮边框动态动画
前端·css·css3
rookie_fly1 天前
基于Vue的数字输入框指令
前端·vue.js·设计模式
元直数字电路验证1 天前
ASP.NET Core Web APP(MVC)开发中无法全局配置 NuGet 包,该怎么解?
前端·javascript·ui·docker·asp.net·.net
rexling11 天前
【Spring Boot】Spring Boot解决循环依赖
java·前端·spring boot
我有一棵树1 天前
Vue 项目中全局样式的正确写法:不要把字体和主题写在 #app 上
前端·javascript·vue.js
Luna-player1 天前
npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本,解决方法
前端·npm·node.js
悢七1 天前
windows npm打包无问题,但linux npm打包后部分样式缺失
linux·前端·npm