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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.