Kevin Skayro Site Logo
Front-end Development,  JavaScript,  Vue

What is and how to use "Props" - Vue.js

Author

Kevin Skayro

Date Published

what_is_and_how_to_use_props_vue

There are a few things you can do to pass data in between components, we can use provide/inject and we also have props.

In this situation, we'll talk about props but if you want to know more about provide/injectread this article.

The props (short for properties) are a way to pass data from a parent component to a child component. Props are used to make a component more reusable by allowing the component to accept different data as input.

To use props in a Vue component, you first need to define the props that the component accepts. This is done in the component's props option. For example, if a component accepts a prop called "message", you would define it like this:

1props: {
2 message: {
3 type: String,
4 required: true
5 }
6}

This tells Vue that the component expects to receive a prop called "message" that is a string and is required.

Once you've defined the props that a component accepts, you can pass data to it when you use the component. This is done by binding the data to the prop in the HTML template. For example, if you have a component called "MyComponent" that accepts a prop called "message", you can use it like this:

1<template>
2 <div>
3 <MyComponent :message="someData" />
4 </div>
5</template>
6
7<script>
8export default {
9 data() {
10 return {
11 someData: 'Hello World'
12 }
13 }
14}
15</script>

This passes the value of the data property someData to the message prop of the MyComponent component.

In the child component you can use it by referencing to it as this.message in the template or methods.

1<template>
2 <div>
3 {{ message }}
4 </div>
5</template>

If you wish to learn more about props you can read the official Vue documentation here.