In Vue, props are a way to pass data from a parent component down to its child components.
They are custom attributes we can register on a component, and the parent component can pass data to the child component via these props.
Props are read-only data and cannot be modified by the child component.
Unidirectional Data Flow: Props are passed from parent to child components in a unidirectional flow. Child components cannot directly modify the props passed to them.
Type Validation: Vue.js provides built-in prop validation to ensure that the received data is of the correct type. we can specify the expected type of each prop.
One-Way Binding: Props are bound in a one-way manner. Changes to props in the parent component are automatically reflected in the child component, but changes in the child component do not affect the parent.
In the parent component's template, we bind values to the props using the "v-bind" directive or shorthand ":".
<template> <child-component :propA="dataA" :propB="dataB" :propC="dataC" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { dataA: 'Alice Collin, dataB: 26, dataC: true } } } </script>
"propA", "propB", and "propC" are props defined in the child component.
The parent component passes data to these props using "v-bind" or ":" in the template.
"props" are "uni-directional", meaning the parent passes data to the child. If the child component needs to communicate back with the parent, it can "emit" events that the parent can listen to.
// In ChildComponent.vue file <script> export default { props: { propA: String, propB: Number, propC: { type: Boolean, required: true // propC is required } } } </script>
In the child component, we define props as an array of strings or an object specifying the props' name and optional type validation.
<!-- ChildComponent.vue --> <template> <button @click="emitEvent">Click me!</button> </template> <script> export default { methods: { emitEvent(eventData) { this.$emit('custom-event', eventData); } } } </script>
On button click the `emitEvent` function will invoked and it will emit an event named "custom-event" from the child Component.
<!-- ParentComponent.vue --> <template> <ChildComponent @custom-event="handleCustomEvent" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleCustomEvent() { // Handle the custom event } } } </script>
From the child component, an event has been emitted and we can bind the local function in the parent component with that event.
when we click from the child component it will invoke function in the parent component.