How to set default value of props in VueJS ?

featured Image

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?

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more