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