What Is the Data Flow Followed by Props in Vue.js

In Vue.js, props are a way to pass data from a parent component down to its child components. Props allow you to create a unidirectional data flow, where changes in the parent component can be passed down to child components, but not vice versa. Let's explore the data flow followed by props in Vue.js with detailed code examples:

Defining Props in Parent Component

In the parent component, you define props as attributes in the child component's tag. These props can be bound to data properties in the parent component.

<!-- ParentComponent.vue -->
<template>
  <ChildComponent :message="parentMessage"></ChildComponent>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Hello from Parent Component'
    };
  }
}
</script>

Receiving Props in Child Component

In the child component, you receive props through the props option in the component's configuration object. Props are then accessible as properties on the props object.

<!-- ChildComponent.vue -->
<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  props: ['message']
}
</script>

Using Props in Child Component Template

Once props are received in the child component, you can use them directly in the template.

<!-- ChildComponent.vue -->
<template>
  <div>{{ message }}</div>
</template>

Updating Props in Parent Component

Props are reactive in Vue.js, meaning if the data bound to a prop in the parent component changes, the change will be automatically reflected in the child component.

<!-- ParentComponent.vue -->
<template>
  <button @click="updateMessage">Update Message</button>
  <ChildComponent :message="parentMessage"></ChildComponent>
</template>

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

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      parentMessage: 'Hello from Parent Component'
    };
  },
  methods: {
    updateMessage() {
      this.parentMessage = 'Updated Message';
    }
  }
}
</script>

In this flow, the parent component passes data down to the child component through props. Any changes to the data in the parent component will automatically propagate to the child component, updating its props and triggering re-rendering if necessary. However, the child component cannot directly mutate the props received from the parent, ensuring a unidirectional data flow.