Course Content
VUE Tutorial
About Lesson

Props

Vue.js, often simply referred to as Vue, is a progressive JavaScript framework used for building user interfaces. It is designed from the ground up to be incrementally adaptable, making it easily integrated into existing projects. In this post, we delve into one of Vue.js’s key concepts – Props.

What are Props in Vue.js?

Props, short for properties, allow communication between components in a Vue application. They enable the passing of data from a parent component to a child component. This mechanism facilitates the creation of dynamic and flexible applications, as components can be reused with different sets of data.

Declaring Props

In Vue, props are declared in the child component’s props option. This defines the expected properties and their types. When a parent component passes data to a child component, it becomes accessible as a prop within the child component.

Syntax for Props

Let’s explore the syntax for declaring and using props in Vue.js:

// ChildComponent.vue

<template>
<div>
<p>{{ receivedProp }}</p>
</div>

</template>

<script>
export default {
props: {
receivedProp: String
}
}
</script>

In this example, the child component expects a prop named receivedProp of type String.

Passing Props from Parent to Child

To pass data from a parent component to a child component, you use the v-bind directive in the parent’s template. Here’s how you can achieve this:

// ParentComponent.vue

<template>
<div>
<ChildComponent :receivedProp="parentData" />
</div>

</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
components: {
ChildComponent
},
data() {
return {
parentData: 'Hello from parent!'
};
}
}
</script>

In this example, the parent component sets the value of parentData, and it gets passed as the prop receivedProp to the child component.

Dynamic Props

Vue allows props to be dynamic by binding them to a variable. This enables the creation of more flexible and interactive components.

// ParentComponent.vue

<template>
<div>
<ChildComponent :receivedProp="dynamicData" />
</div>

</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
components: {
ChildComponent
},
data() {
return {
dynamicData: 'Dynamic prop value'
};
},
methods: {
updateDynamicData() {
this.dynamicData = 'Updated dynamic prop value';
}
}
}
</script>

In this scenario, changing the value of dynamicData in the parent component dynamically updates the prop in the child component.