vue.jsobjectvuejs3nuxtjs3vue-props

Vue: How to merge object props with default values


I want to set an object title as a prop with type and text inside. As a default, I want to set only the default value for type to be h2.

When title: {text: 'Some text'} is passed as props, I want to merge it with the default values so the result would be title: {type: 'h2', text: 'Some text'}.

How can I achieve this? Using Object.assign can be used but I'm not sure how in this case.

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

withDefaults(defineProps<Props>(), {
  title: () => {
    return {
      type: 'h2',
      text: null,
    }
  },
})

Solution

  • 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,
    }))