Component Props play a crucial role in passing down state to child components. In this blog post, we will explore various aspects of props and how to use them effectively.
Table of Contents
- Define a prop inside the component
- Accept multiple props
- Set the prop type
- Set a prop to be mandatory
- Set the default value of a prop
- Passing props to the component
Define a prop inside the component
Props allow components to accept data from parent components. To define a prop inside a component, we can use the props
property like this:
Vue.component('user-name', {
props: ['name'],
template: '<p>Hi {{ name }}</p>'
})
Alternatively, in a Vue Single File Component, we can define props using the props
object:
<template>
<p>{{ name }}</p>
</template>
<script>
export default {
props: ['name']
}
</script>
Accept multiple props
We can pass multiple props to a component by appending them to the props array:
Vue.component('user-name', {
props: ['firstName', 'lastName'],
template: '<p>Hi {{ firstName }} {{ lastName }}</p>'
})
Set the prop type
To specify the type of a prop, we can use an object instead of an array in the props property. The name of the property serves as the key, and the type serves as the value:
Vue.component('user-name', {
props: {
firstName: String,
lastName: String
},
template: '<p>Hi {{ firstName }} {{ lastName }}</p>'
})
The valid prop types include:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
Vue will issue a warning in the console if the provided type does not match the defined prop type.
Set a prop to be mandatory
If we want to make a prop mandatory, we can specify the required
flag in the props object:
props: {
firstName: {
type: String,
required: true
}
}
Set the default value of a prop
To set a default value for a prop, we can specify the default
field in the props object:
props: {
firstName: {
type: String,
default: 'Unknown person'
}
}
For objects, we can specify a default value using an object literal:
props: {
name: {
type: Object,
default: {
firstName: 'Unknown',
lastName: ''
}
}
}
Instead of providing the actual default value, we can also use a function that returns the appropriate value.
Passing props to the component
To pass a prop to a component, we can use the syntax:
<ComponentName color="white" />
If the value is static.
If we want to pass a data property as a prop, we can use the following syntax:
<template>
<ComponentName :color=color />
</template>
<script>
...
export default {
//...
data: function() {
return {
color: 'white'
}
},
//...
}
</script>
We can also use a ternary operator to conditionally pass a prop value based on a truthy condition:
<template>
<ComponentName :colored="color == 'white' ? true : false" />
</template>
<script>
...
export default {
//...
data: function() {
return {
color: 'white'
}
},
//...
}
</script>
Overall, understanding and effectively using props in Vue.js components is essential for building flexible and reusable components.