Search code examples
typescriptvue.jsvuejs3vue-script-setup

Vue3 - script setup use 'withDefaults' for nested object,it attributes become required,how to fixed it?


I defined a props:

interface Props {
  formList: BaseSearchFormListItemType[],
  inline?: boolean
  searchBtn?: {
    show?: boolean
    text?: string
    type?: string
    size?: string
  }
}
const props = withDefaults(defineProps<Props>(), {
  inline: true,
  searchBtn: () => ({
    show: true,
    type: 'default',
    text: '查询',
    size: 'default'
  })
})

searchBtn has four attributes not required, but when I use this child-component,

<BaseSearch
  :formList="searchFormList"
  :search-btn="{
  show: true
  // type: 'default',
  // text: '查询',1
  // size: 'default'
  }"
  :inline="false"/>

that four attributes become required,how can i fixed it? enter image description here

when i delete default value , it can work, but i need the default value.


Solution

  • define a compute prop like this:

    const defaultSearchBtn = {
      show: true,
      type: 'default',
      text: '查询',
      size: 'default',
    }
    const props = withDefaults(defineProps<Props>(), {
      inline: true,
      searchBtn: () => ({ show: true, type: 'default', text: '查询', size: 'default' }),
    })
    const innerSearchBtn = computed(() => {
      return { ...defaultSearchBtn, ...props.searchBtn }
    })