Home > Net >  Vue composition API - how to define default props for specific props?
Vue composition API - how to define default props for specific props?

Time:02-04

I have a component in Options API that I migrate to Composition API & typescript. The component looks like this:

<script>

export default {
  props: {
     value: {
        type: String,
        required: true
     },
     disabled: {
        type: Boolean,
        default: false
     }
  },
  // ...
}

I tried to use withDefaults and defineProps:

<script lang="ts" setup>

interface Props {
  value: string
  disabled: boolean
}

const props = withDefaults(defineProps<Props>, {
  disabled: false
})

But withDefaults makes all props optional. I want value to be a required prop. How can I achieve this? Offical docs doesn't help.

CodePudding user response:

props: {
    height: Number,
    age: {
      type: Number,
      default: 0,
      required: true, // value age now is required
    }
  }

CodePudding user response:

As @Barks said in comment, in Vue with Typescript the optional/required props are inferred from the props definition. withDefaults just adds default values, and does not change the props type definition. In my case:

interface Props {
  value: string
  disabled?: boolean // ? - for optional prop
}

const props = withDefaults(defineProps<Props>, {
  disabled: false
})
  • Related