Using Provide/Inject for State Sharing in Vue 3
Show how to use the provide and inject API in Vue 3 to pass state deeply into the component tree without prop drilling.
// ParentComponent.vue
<template>
<!-- ... -->
</template>
<script setup>
import { provide } from 'vue';
const sharedState = reactive({ count: 0 });
provide('sharedState', sharedState);
</script>
In the parent component, we define and provide the shared state using Vue's reactive system and the provide function.
// ChildComponent.vue
<template>
<!-- ... -->
</template>
<script setup>
import { inject } from 'vue';
const sharedState = inject('sharedState');
// Use sharedState.count to access the reactive count property
</script>
In the child component, we inject the provided shared state. This allows us to access the reactive state properties without prop drilling.
// DeepChildComponent.vue
<template>
<button @click="sharedState.count++">Increment</button>
</template>
<script setup>
import { inject } from 'vue';
const sharedState = inject('sharedState');
// Increment function is used to change the count
</script>
In a deeply nested child component, we inject the shared state and bind a button's click event to increment the count property of the shared state.