Categories
JavaScript Vue

How to Pass Data to a Vue.js Component

Spread the love

We can pass data to a Vue.js component via props.

To do that, we add a props property to a component.

For instance, we can write:

Vue.component('blog-post', {
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})

In the code above, we have the blog-post component that takes the postTitle prop.

Then we can use the blog-post component and pass the postTitle prop to it by writing:

<blog-post post-title="hello!"></blog-post>

The prop name is written in kebab-case, but it’ll be mapped to camelCase.

To make the prop passing mechanism more robust, we can set the data type that it takes.

We can do that by writing:

props: {
  postTitle : String
}

The value can be set to any other JavaScript constructor.

In our example, it’s set to String, so postTitle must be a string.

Otherwise, we’ll get an error from Vue.

If we want to pass a dynamic prop, then we’ve to use the v-bind directive or : for short.

For instance, we can write:

<blog-post :post-title="post.title"></blog-post>

or:

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

Passing prop values are the way that we pass data to a Vue.js component.

We use the props property, which can be an object or array to indicate the props we want to accept.

If it’s an object, then the value can be any constructor to let us validate that that what’s passed in is the instance of that constructor.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.