Skip to content

Vue Composition API: Props

Mike Lyttle edited this page May 9, 2023 · 1 revision

Class Component

import { Prop } from "vue-property-decorator";
    @Prop({ type: String, required: true })
    requiredProp!: string;
    
    @Prop({ type: String, default: "Hello!" })
    optionalProp!: string;

Composition API

interface Props {
    requiredProp: string;
    optionalProp?: string;
}
withDefaults(defineProps<Props>(), {
    optionalProp: "Hello!",
});

Notes

  • If the props don't have default values, withDefaults is not needed.

    interface Props {
        requiredProp: string;
    }
    defineProps<Props>();
  • Props can be accessed directly in the template without any qualifiers (e.g. {{ requiredProp }}).

    To access them in the script, the Props object returned by defineProps or withDefaults must be assigned to a variable, where the props can be accessed as properties.

    import { computed } from "vue";
    
    interface Props {
        requiredProp: string;
    }
    const props = defineProps<Props>();
    
    const greeting = computed(
      () => `We just wanted to say "${props.requiredProp}"`
    );
  • Defaults for arrays and other objects must be returned from a function.

    interface Props {
        optionalArray?: string[];
    }
    withDefaults(defineProps<Props>(), {
        optionalArray: () => [],
    });

Documentation

Clone this wiki locally