How to Use Props in Vue.js with Examples

Published on April 1, 2020 1 min read

In this article, I’m going to share how to use props in Vue.js. Let’s get started:

Table of Contents

  1. Type Checks
  2. Register Props
  3. Pass Data to Props
  4. Pass Function to Props
  5. Set Validation

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:

Button.vue
<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:

App.vue
<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.

Button.vue
<template>
  <button @click="handleClick">{{title}}</button>
</template>

<script>
 export default{
  props: ['title', 'handleClick']
 }
</script>

Now pass a function to the prop like:

App.vue
<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.

Button.vue
<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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *