← Back to all snippets
JAVASCRIPT

Implementing Cross-Component Communication with Vue 3's provide and inject

Understand how to share state or functions across deeply nested components in Vue 3 using the `provide` and `inject` API, simplifying complex prop passing.

// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <p>User Name: {{ userName }}</p>
    <ChildComponent />
  </div>
</template>

<script>
import { ref, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: { ChildComponent },
  setup() {
    const userName = ref('Alice Smith');

    // Provide a reactive value and a function
    provide('userNameKey', userName);
    provide('updateUserName', (newName) => {
      userName.value = newName;
    });

    return { userName };
  }
};
</script>

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <GrandchildComponent />
  </div>
</template>

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

export default {
  components: { GrandchildComponent }
};
</script>

// GrandchildComponent.vue
<template>
  <div>
    <h3>Grandchild Component</h3>
    <p>Injected User Name: {{ injectedUserName }}</p>
    <button @click="changeName">Change Name from Grandchild</button>
  </div>
</template>

<script>
import { inject } from 'vue';

export default {
  setup() {
    // Inject the provided values
    const injectedUserName = inject('userNameKey');
    const updateUserName = inject('updateUserName');

    const changeName = () => {
      if (updateUserName) {
        updateUserName('Bob Johnson');
      }
    };

    return {
      injectedUserName,
      changeName
    };
  }
};
How it works: This example demonstrates how Vue 3's `provide` and `inject` work to facilitate communication between components that are not directly parent-child. The `ParentComponent` uses `provide` to make `userName` (a reactive ref) and an `updateUserName` function available. Nested components, like `GrandchildComponent`, can then use `inject` to access these provided values and functions without needing to pass them down through every intermediate component as props. This pattern is ideal for global state-like data or utility functions that many deeply nested components might need, significantly reducing prop-drilling.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs