How to set default value of props in VueJS ?

In this article, we will learn how to set default values in props in VueJs.

Since Vue is a component-based framework, props are properties in Vuejs that are passed from the parent component to its child components. Through these, parent and child components, we end up building a data structure called a tree.

Default values are values that are assigned to the props when no specific value is explicitly assigned to the props.

Types of props that we can use in Vuejs are:

  1. String
  2. Number
  3. Boolean
  4. Array
  5. Object
  6. Date
  7. Function
  8. Symbol

Below are the default values we can set for different types of props in VueJS.

Set Default values of props in VueJS

1. Default value of String props

 props: {
      name:{
        type: String,
        default: 'John'
      }
   },

2. Default value of Number props

 props: {
      price:{
        type: Number,
        default: 100
      }
   },

3. Default value of Boolean prop

 props: {
      isActive:{
        type: Boolean,
        default: true
      }
   },

4. Default value of Function prop.

For Function, defaults must be returned from a factory function

 props: {
      getData:{
        type: Function,
        default: function () {
          return 1;
        }
      }
   },

4. Default value of Object prop.

For Objects, defaults must be returned from a factory function

 props: {
      employee:{
        type: object,
        default: function () {
          return { name: 'Mark', age: 26 }
        }
      }
   },

4. Default value of Array prop.

For Array too, the default must be a return function.

props: {
    items: {
        type: Array,
        default: () => ['item1','item2']
    }
}

This is how you can set default values in different props data types in VueJS application.

Related Topic:

How to call a function in VUE template?

Scroll to Top