[Vuejs]-Vue: How to merge object props with default values

0👍

You can achieve this with a computed like that

export interface Props {
  title: {
    type: 'h1' | 'h2'
    text: string
  }
}

const props = defineProps<Props>()

const preparedTitle = computed(() => ({
  type: 'h1',
  ...props.title
}))

Another way is to make titleType and titleText separate props

export interface Props {
  titleType: 'h1' | 'h2'
  titleText: string
}

const props = withDefaults(defineProps<Props>(), {
  titleType: 'h1'
})

// You can optionally merge them back if you really need to
const title = computed(() => ({
  type: props.titleType,
  text: props.titleText,
}))

Leave a comment