Table of contents
1.
Introduction
2.
Props in Vue
2.1.
Types of Props in Vue.js
3.
Static or Dynamic Props passing
3.1.
Passing a Number
3.2.
Passing a Boolean
3.3.
Passing an Array
3.4.
Passing an Object
3.5.
Passing the Properties of an Object
4.
One Way Data Flow
5.
Prop Validation
6.
Type Checks
7.
Prop Casing: camelCase vs kebab-case
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Props- Vue.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Props and data are two alternative types of storing variables included with Vue. These can be perplexing at first because they appear to do the same thing, and it's unclear when to employ one over the other.

So, what exactly is the distinction between props and data?

Data is each component's own memory, where you can store any variables you require. Props are the means by which data is passed from a parent component to a child component.

Props in Vue

In Vue, props (or properties) are how we pass data from a parent component down to its child components.

We create a data structure called a tree when we build our apps out of components. You have the following, similar to a family tree:

  • parents
  • children
  • ancestors
  • and descendants

Data goes down this tree from the very top, the root component. Parent components transmit props down to their children in the same way that genetics is passed down from generation to generation.

The <template> part of our code in Vue is where we add props to components:

<template>
  <my-component cool-prop="hello world"></my-component>
</template>

 

In this example, we pass the prop cool-prop a "hello world" value. We will be able to access this value from inside of my component.

However, when we access props from inside of a component, we don't own them, so we can't change them (just like you can't change the genes your parents gave you).

Types of Props in Vue.js

More often, props in Vue.js are listed as an array of strings. It is shown as follows:

props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

 

However, you'll almost always want each parameter to be a certain sort of value. You can list props as an object in these cases, with the names and values of the properties including the prop names and types, respectively:

props: {
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise // or any other constructor
}

Static or Dynamic Props passing

Props have been passed a static value so far, as in

<blog-post title="My journey with Vue"></blog-post>

 

Props can also be assigned dynamically using v-bind or its shortcut: 

<!-- Assigning a variable's value dynamically.-->
<blog-post :title="post.title"></blog-post>

 
<!-- Assigning the value of a complex expression dynamically -->
<blog-post :title="post.title + ' by ' + post.author.name"></blog-post>

 

We happen to pass string values in the two examples above, but any type of value can actually be passed to a prop.

Passing a Number

<!-- We need v-bind to tell vue that '42' is static -->
<!-- this is a JavaScript expression not a string        -->
<blog-post :likes="42"></blog-post>

 
<!-- Assigning to the value of a variable dynamically -->
<blog-post :likes="post.likes"></blog-post>

Passing a Boolean

<!-- no value props will imply `true`. -->
<!-- If you don't set the is-published type to Boolean in props, it will be an empty string instead of "true" value. -->
<blog-post is-published></blog-post>

 
<!-- Even though `false` is static, we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression not a string           -->
<blog-post :is-published="false"></blog-post>

 
<!-- Dynamically assign to the value of a variable. -->
<blog-post :is-published="post.isPublished"></blog-post>

Passing an Array

<!--we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression not a string even though array is static            -->
<blog-post :comment-ids="[234, 266, 273]"></blog-post>

 
<!-- Dynamically assign to the value of a variable. -->
<blog-post :comment-ids="post.commentIds"></blog-post>

Passing an Object

<!-- we need v-bind to tell Vue that -->
<!-- this is a JavaScript expression rather than a string, even though the object is static,             -->
<blog-post
  :author="{
    name: 'Veronica',
    company: 'Veridian Dynamics'
  }"
></blog-post>

 
<!-- assign the value of a variable dynamically -->
<blog-post :author="post.author"></blog-post>

Passing the Properties of an Object

You can use v-bind without an argument to pass all of an object's properties as props (v-bind instead of:prop-name). 

Given a post object, for example:

post: {
  id: 1,
  title: 'My Journey with Vue'
}

The following template:

<blog-post v-bind="post"></blog-post>

Will be equivalent to:

<blog-post v-bind:id="post.id" v-bind:title="post.title"></blog-post>

One Way Data Flow

All props constitute a one-way-down binding between the child and parent properties. When the parent property updates, it will flow down to the child, but not vice versa. This prevents child components from changing the parent's state by inadvertently, making your app's data flow more difficult to understand.

Furthermore, if the parent component is updated, all props in the child component are updated with the most recent value. This means you shouldn't try to change a prop from within a child component. If you do, Vue will issue a console warning.

It's always enticing to modify a prop in one of two situation:

  1. The Vue.js prop is used to pass in an initial value, which the child component then wants to use as a local data property. It's better to create a local data property that utilizes the prop as its initial value in this case:
props: ['initialCounter'],
data() {
  return {
    counter: this.initialCounter
  }
}

 

 2. The prop is given as an unprocessed value that must be converted. It's better to define a calculated property using the prop's value in this case:

props: ['size'],
computed: {
  normalizedSize() {
    return this.size.trim().toLowerCase()
  }
}

 

Note: Note that with JavaScript, objects and arrays are sent via reference, therefore if the prop is an array or object, changing the object or array inside the child component will impact the parent state, and Vue will not notify you. 

As a general guideline, you should avoid altering any prop, including objects and arrays, because this violates one-way data binding and might lead to unexpected effects.

Prop Validation

Components can provide prop requirements, such as the types you've seen thus far. Vue will tell you in the browser's JavaScript console if a condition isn't met. This is very helpful when creating a component that will be utilized by others.

Instead of an array of strings, you can pass an object containing validation criteria to the value of props to provide prop validations. Consider the following scenario:

app.component('my-component', {
  props: {
    // Basic type validation (values of 'null' and 'undefined' will pass any type validation)
    propA: Number,
    //There can be multiple possible types
    propB: [String, Number],
    // Required string
    propC: {
      type: String,
      required: true
    },
    // Number type with a default value
    propD: {
      type: Number,
      default: 100
    },
    // Object type with a default value
    propE: {
      type: Object,
      // A factory function must return object or array defaults.
 
      default() {
        return { message: 'hello' }
      }
    },
    // Custom validator function
    propF: {
      validator(value) {
        // One of these strings must match the value.
        return ['success', 'warning', 'danger'].includes(value)
      }
    },
    // a default value function
    propG: {
      type: Function,
      // This is not a factory function like object or array default; instead, it is a function that serves as a default value.
      default() {
        return 'Default function'
      }
    }
  }
})

 

Vue will issue a console warning if prop validation fails (if using the development build).

Note that because props are validated before a component instance is formed, instance properties (such as data, calculated, and so on) will not be available within default or validator functions.

Type Checks

The types in props Vue.js can be one of the following native constructors:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

In addition, type can be a custom constructor function, and an instanceof check will be used to make the assertion. Given the existence of the constructor function below:

function Person(firstName, lastName) {
  this.firstName = firstName
  this.lastName = lastName
}

 

You could use:

app.component('blog-post', {
  props: {
    author: Person
  }
})

 

To ensure that the author prop's value was created with a new Person.

Prop Casing: camelCase vs kebab-case

Because the names of HTML attributes are case-insensitive, browsers will treat any capital letters as lowercase. That means camelCased prop names must be replaced with their kebab-cased (hyphen-delimited) equivalents when utilizing in-DOM templates:

const app = Vue.createApp({})

 
app.component('blog-post', {
  // camelCase in JavaScript
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})
<!-- kebab-case in HTML -->
<blog-post post-title="hello!"></blog-post>

Again, this limitation does not apply if you're using string templates.

FAQs

  1. How do you handle props in Vue?
    To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
     
  2. What is the use of props in Vue JS?
    In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components. When we build our applications out of components, we end up building a data structure called a tree.
     
  3. What is V bind in Vue?
    The v-bind directive is a Vue. js directive used to bind one or more attributes, or a component prop to an element. If that attribute is bonded to our data defined in Vue instance then dynamically changes can be observed as data changes.

Key Takeaways

Props and data are two alternative types of storing variables included with Vue.

In Vue, props (or properties) are how we pass data from a parent component down to its child components.

For more Vue.JS related articles, please visit the following links:

  1. Security in Vue
  2. Production deployment in Vue

Thanks for choosing us. Happy learning!

Live masterclass