How to set default value of props in VueJS ?
This article is on how to set default values in props in VueJS. Default values are used when the props are not passed from parent component to its child component.
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:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- 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:
Related Posts
How to pass data from parent component to child using props in Vue
Find out how to send data from parent component to child component using props in Vue.
Execute a function from child component in Vue
Find out how we can execute a function in the parent component from the child component using emit function in Vue.
Pass multiple objects as props in Vue
Short tutorial on how to pass multiple objects as props to a child component from parent in vue using v-for directive.
How to pass multiple props to component in Vue
Short article on how to pass multiple props to a component in vue using v-bind.
