Introduction to Vue.js Props

/ #Vue.js


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 Vue.js apps.

Other Vue.js tutorials

-A short introduction to Vue.js watchers
-Vue.js filters

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.