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

相关推荐
李鸿耀2 小时前
Flex 布局下文字省略不生效?原因其实很简单
前端
皮蛋瘦肉粥_1213 小时前
pink老师html5+css3day06
前端·css3·html5
华仔啊7 小时前
前端必看!12个JS神级简写技巧,代码效率直接飙升80%,告别加班!
前端·javascript
excel7 小时前
dep.ts 逐行解读
前端·javascript·vue.js
爱上妖精的尾巴7 小时前
5-20 WPS JS宏 every与some数组的[与或]迭代(数组的逻辑判断)
开发语言·前端·javascript·wps·js宏·jsa
excel7 小时前
Vue3 响应式核心源码全解析:Dep、Link 与 track/trigger 完整执行机制详解
前端
前端大卫7 小时前
一个关于时区的线上问题
前端·javascript·vue.js
whltaoin8 小时前
中秋赏月互动页面:用前端技术演绎传统节日之美
前端·javascript·html·css3·中秋主题前端
IT派同学8 小时前
TableWiz诞生记:一个被表格合并逼疯的程序员如何自救
前端·vue.js
西洼工作室11 小时前
CSS高效开发三大方向
前端·css