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:
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:
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 typerequired- whether the prop is requireddefault- the default valuevalidator- a custom check
2. Declaring props in the Composition API: setup()
If you use setup(), props are passed as the first argument:
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:
const { title } = props // reactivity is lostCorrect:
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:
<script setup>
const props = defineProps({
title: String,
count: Number
})
</script>You can destructure right away (reactivity is preserved!):
<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)
<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 readyA concise answer to help you respond confidently on this topic during an interview.