Introduction to Vue.js Props

Introduction to Vue.js Props

Published 23. jun 2018 12:11 by Stein Ove Helset

Props are used to pass data from a component to another. In this post we will go through how you can pass strings, objects and other data types.

The easiest way to pass a string is to just define the prop in a array like this:


Vue.component('alert-box', {
  props: ['content'],
  template: '<div class="alert">{{ content }}</div>
})

<alert-box content="The alert message"></alert-box>

If you're not just sending a string or two it might be a good idea to specify which type of prop you're sending. There are several different valid types like:
-String
-Boolean
-Number
-Array
-Function

Here is the syntax for specifying type:


Vue.component('alert-box', {
  props: {
    content: {
      type: String,
    },
  },
  template: '<div class="alert">{{ content }}</div>
})

<alert-box content="The alert message"></alert-box>

If you want to make one of the props required or set a default value, you can do that too:


Vue.component('alert-box', {
  props: {
    content: {
      type: String,
      required: true,
    },
    errors: {
      type: Number,
      default: 0,
    },
  },
  template: '<div class="alert">{{ content }}. Errors: {{ errors }}</div>
})

<alert-box content="The alert message"></alert-box>

It's also nice to be able to pass a object:


Vue.component('alert-box', {
  props: {
    content: {
      type: Object,
    },
  },
  template: '<div class="alert">{{ content.title }}. Errors: {{ content.errors }}</div>
})

<alert-box content="{title: 'The alert message', errors: 2}"></alert-box>

Summary

Now you should be able to pass whatever kind of data type you want. This is an important thing to know and will help you further when building an Vue.js app.

Read more about Vue on A Hacker's Day:
Introduction to Vue.js Filters
Introduction to Vue.js Slots
Communicating between Vue.js components

Share this post

Comments

No comments yet

Add comment