Passing Data with Props in Vue.js
Introduction
In this tutorial, we will explore one of the most fundamental parts of Vue.js, which is passing data with props. Props are a way to pass data from parent components to child components. This is a powerful feature that allows us to build complex applications with a component-based structure.
What are Props in Vue.js?
Props, short for properties, are used to pass data from a parent component to a child component. This mechanism works in a unidirectional flow that means the data is passed from the parent to child and not vice versa.
How to Define Props in Vue.js
In Vue.js, we define props inside the child component using the props
option, which can be an array or an object. Here's an example of how we can define a prop:
<script>
export default {
props: ['title']
}
</script>
In the example above, we've defined a prop named title
. Now, this prop can be used inside the child component's template just like a data property.
Passing Data with Props
To pass data from the parent component to the child component, we need to bind it to a prop. This can be done using the v-bind
directive. Let's take a look at an example:
<template>
<child-component v-bind:title="parentTitle"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
data() {
return {
parentTitle: 'Hello, Vue!'
}
},
components: {
ChildComponent
}
}
</script>
In the example above, we have a data property parentTitle
in the parent component. We are passing this data to the child-component
using the v-bind
directive.
Now, in the child component, we can use this prop as follows:
<template>
<h1>{{ title }}</h1>
</template>
<script>
export default {
props: ['title']
}
</script>
In the child component, we are using the title
prop in the template to render it as a heading.
Props Validation
Vue.js also allows us to validate the props that we pass to child components. We can specify the type of the prop, whether it is required or not, and even provide a default value. Here's an example:
<script>
export default {
props: {
title: {
type: String,
required: true,
default: 'Hello, Vue!'
}
}
}
</script>
In the example above, we've defined that the title
prop should be of type String
, it is required, and if no value is provided, the default value 'Hello, Vue!'
will be used.
Conclusion
Props in Vue.js are a simple and effective way to pass data from parent components to child components. They are a key part of building reusable and manageable components. We've learned how to define props, pass data with props, and validate props. Happy coding!