JavaScript/vue.js/defineProps

来自康健生活
Kangkk​(留言 | 贡献)2025年4月11日 (五) 08:17的版本 (→默认值)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

默认值

vue 3.5.0+ 响应式 Props 解构

const {
  type = 'number',
  useColor = false,
  usePrefix = false,
  value,
  title = '',
  color = '#ffffffff',
} = defineProps({
  type: String as PropType<'number' | 'string'>,
  useColor: Boolean,
  usePrefix: Boolean,
  value: [Number, String] as PropType<number | string>,
  title: String,
  color: [String, undefined] as PropType<ColorInputWithoutInstance>,
})

vue 3.4.0- 使用 withDefaults 提供默认值

const props = withDefaults(
  defineProps<{
    type?: 'number' | 'string'
    useColor?: boolean
    usePrefix?: boolean
    value?: number | string
    title?: string
    color?: ColorInputWithoutInstance
  }>(),
  {
    title: '',
    type: 'number',
    useColor: false,
    usePrefix: false,
    value: (props: any) => (props.type === 'number' ? 0 : ''),
    color: '#ffffffff',
  },
)