← Back to Vue.js Course | Chapter 6: Component Communication | Lesson 7 of 7

Default props

Optional props can have a default value used when the parent does not pass one.

In this page:

  1. Default props
Syntax
markup
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

markup
<!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
  1. Using a shared object as an array default
  2. Expecting undefined to override a default
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.