How to set default value of props in VueJS ?


In this article we will learn on how to set default value in props in VueJs.

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

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

Types of props that we can use in Vuejs are:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

Below are the default values we can set to 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 value in different props data types in VueJS application.

Related Topic:

How to call a function in VUE template?


💾 Recommended Articles