Skip to main content

How do you declare props?

Props can be declared in two ways, depending on which API you use: Options API or Composition API (setup / <script setup>). At an interview it is important to know both.


1. Declaring props in the Options API

In the component you specify a props object:

js
export default { props: { title: String, count: Number, isActive: Boolean, } }

Each property is a prop that can be passed by the parent.

You can specify an extended configuration:

js
props: { title: { type: String, required: true }, count: { type: Number, default: 0 }, user: { type: Object, default: () => ({}) // important: objects through a function } }

Arguments in the Options API

You can set:

  • type - the data type
  • required - whether the prop is required
  • default - the default value
  • validator - a custom check

2. Declaring props in the Composition API: setup()

If you use setup(), props are passed as the first argument:

js
export default { props: { title: String, count: Number }, setup(props) { console.log(props.title) console.log(props.count) } }

Important: props are read-only, they cannot be changed.


Destructuring in setup() → you lose reactivity

You cannot do this:

js
const { title } = props // reactivity is lost

Correct:

js
import { toRefs } from 'vue' const { title, count } = toRefs(props)

3. Declaring props in <script setup> (Vue 3)

This is the most convenient and modern way.

It uses the defineProps() function:

vue
<script setup> const props = defineProps({ title: String, count: Number }) </script>

You can destructure right away (reactivity is preserved!):

vue
<script setup> const { title, count } = defineProps({ title: String, count: Number }) </script>

Why can you destructure in <script setup>?

Because defineProps calls toRefs under the hood, if you destructure, Vue itself turns the properties into reactive refs.


Example with prop types (extended)

vue
<script setup> const props = defineProps({ user: { type: Object, required: true }, list: { type: Array, default: () => [] }, isActive: Boolean, count: { type: Number, default: 1, }, validatorProp: { validator: v => ['small', 'medium', 'large'].includes(v) } }) </script>

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.