Default props
Optional props can have a default value used when the parent does not pass one.
In this page:
Syntax
props: {
propName: {
type: Type,
default: value
},
listProp: {
type: Array,
default: () => []
}
}
Default props
Give a prop a default in its object definition. For objects and arrays, the default must be a factory function so each instance gets its own copy. Boolean props left out default to false, and a prop passed with no value counts as true.
Note:
Use a function to return default arrays and objects.
Example: Default props
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<greeting-line></greeting-line>
<greeting-line name="Ada" :tags="['math']" loud></greeting-line>
</div>
<script>
const app = Vue.createApp({});
app.component("greeting-line", {
props: {
name: { type: String, default: "friend" },
tags: { type: Array, default: () => ["none"] },
loud: Boolean,
},
template: "<p>{{ loud ? 'HELLO' : 'Hello' }}, {{ name }} [{{ tags.join(',') }}]</p>",
});
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Hello, friend [none]HELLO, Ada [math]
-->
Live Example
Related Topics
Common Mistakes
- Using a shared object as an array default
- Expecting undefined to override a default
- Forgetting booleans default to false
Chapter Summary
- default supplies a fallback
- Object and array defaults use functions
- Absent Boolean props are false
- undefined triggers the default
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: