Props in Vue.js
Gathoni Stone
Posted on April 7, 2020
First, What even are props?😕
According to the official Vue.js docs:
Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
This basically means that props are how we pass data between components; from parent components to child components.
In this post, we're going to look at some of the concepts of Vue.js props.
Defining Props
For a component to register a prop, it has to first define it in its props property.
In a Vue instance,
Vue.component('todo', {
props: ['task'],
template: '<p>Pending {{ task }}</p>'
})
In a Vue component file,
<template>
<p>Pending {{ task }}</p>
</template>
<script>
export default {
name: 'Todo',
props: ['task']
}
</script>
Passing data using props
- Passing a static value
For a component to use the prop, include it as you would a HTML attribute
<Todo task="Learn about Vue.js props"/>
What if you want to pass more than one prop to the component instance? Simple, append the extra props to the array.
<template>
<p>Pending {{ task }} at {{time}}</p>
</template>
<script>
export default {
name: 'Todo',
props: ['task', 'time']
}
</script>
Rendering the component
<Todo task="Learn about Vue.js props" time="10:10 am"/>
- Passing a dynamic value
<template>
<div>
<Todo v-bind:task='task' v-bind:time='time'/> //
</div>
</template>
<script>
export default {
data(){
return {
task: "Learn about Vue.js props",
}
}
</script>
- Passing an array
<template>
<div>
<Todo
v-bind:key="task.id"
v-for="task in tasks"
v-bind:task="task.task"
v-bind:time="task.time"
>
</div>
</div>
</template>
<script>
export default {
data(){
return {
tasks: [
{ id: 1, task: 'Learn about Vue.js props', time: '10:10am' },
{ id: 2, task: 'Go for a walk', time: '06:00pm' },
{ id: 3, task: 'Sleep', time: '11.00pm' }
]
}
}
Prop types
It's always a good thing to define the data types of your props. When props passed don't match the defined type, Vue complains by throwing an error in the console.
To set prop types, you list the props as an object with the properties names as keys and types as values.
props: {
taskId: Number,
task: String,
time: String,
tags: Array,
isCompleted: Boolean,
markComplete: Function
}
To learn more about props, visit the official Vue.js documentation page Vue.js docs
Posted on April 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.