In Vue.js, Provide and Inject is a feature that allows us to provide data, methods, or any other values to child components without needing to pass them through props explicitly.
This is particularly useful for passing data deeply nested in component trees without having to pass it through intermediate components.
Provide and Inject is useful for managing global states, sharing common utilities code, or injecting dependencies into nested child components.
Global State Management: provide and inject can be used to manage global state in your application, allowing any component to access shared data or state without the need for prop drilling.
Dependency Injection: We can inject dependencies or services into components without the need for importing them explicitly in each component, promoting loose coupling and reusability.
Here's how we can use provide and inject in Vue.js:
// services/postService.js export default { getPosts() { // Example of fetching data from an API return fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()); } };
<template> <div> <child-component></child-component> </div> </template> <script> import { provide } from 'vue'; // Import the Post Service import PostService from './services/postService.js'; export default { setup() { // Provide the service with a unique key provide('postservice', PostService); } }; </script>
<template> <div> <ul> <li v-for="post in posts" :key="post.id"> <h2> {{ post.title }} </h2> <p> {{ post.body }} >/p> </li> </ul> </div> </template> <script> import { inject } from 'vue'; export default { setup() { // Inject the provided service using the same key const service = inject('postservice'); // Access methods or properties of the provided service const posts = service.getPosts(); return { posts }; } }; </script>
The provide function is used in the parent component to provide a service `PostService` to its child components.
The inject function is used in the child component to inject the provided service.
The injected value is accessed using the same key ('postservice') provided by the parent component.
Using provide and inject can simplify the passing of data and methods between deeply nested components, as we don't need to pass props through each intermediate component.
It's recommended to use them for providing global services or application-level state, rather than for every piece of data within our components.