How to Use Props in Vue.js with Examples
In this article, I’m going to share how to use props in Vue.js. Let’s get started:
Table of Contents
Type Checks
In Vue, props can be many different things. The type
can be one of the following native constructors:
String
Number
Boolean
Array
Object
Date
Function
Symbol
Register Props
Create a component named Button and paste this code:
<template>
<button>{{title}}</button>
</template>
<script>
export default{
props: ['title']
}
</script>
We’ve registered a prop called title
.
Pass Data to Props
We can pass the data to prop as a custom HTMLÂ attribute like this:
<template>
<div id="app">
<custom-button title="Like"></custom-button>
<custom-button title="Dislike"></custom-button>
</div>
</template>
<script>
import Button from './components/Button.vue'
export default{
components:{
'custom-button': Button
}
}
</script>
Pass Function to Props
We’re able to pass function to props. Let’s modify the Button component and add another prop called handleClick
.
<template>
<button @click="handleClick">{{title}}</button>
</template>
<script>
export default{
props: ['title', 'handleClick']
}
</script>
Now pass a function to the prop like:
<template>
<div id="app">
<custom-button title="Like" :handleClick="likeClickHandel"></custom-button>
</div>
</template>
<script>
import Button from './components/Button.vue'
export default{
components:{
'custom-button': Button
},
methods: {
likeClickHandel: function() {
// logic goes here
console.log("store the like");
}
}
}
</script>
Set Validation
We can also set validation in props. Let’s set validation on title
and handleClick
props.
<template>
<button @click="handleClick">{{title}}</button>
</template>
<script>
export default {
props: {
title:{
required:true,
type:String
},
handleClick:{
required:true,
type:Function
}
}
};
</script>
That’s all. Thank you. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)