在Vue3中使用provide和inject进行依赖注入的代码详解
provide
and inject
for Dependency Injection in Vue 3Vue 3 introduces a built-in mechanism for dependency injection using the provide
and inject
APIs. This allows you to create a hierarchical dependency graph where components can share and access data without the need for explicit prop drilling.
provide
and inject
provide
:
// Parent component
provide('message', 'Hello from parent!');
inject
:
// Child component
const message = inject('message');
console.log(message); // Output: Hello from parent!
provide
and inject
:Consider a scenario where you want to share a message across multiple components in your Vue 3 application:
1. Define the Injection Key:
JavaScript
const messageKey = Symbol('message'); // Unique injection key
2. Provide the Message in the Parent Component:
JavaScript
<script setup>
import { provide } from 'vue';
provide(messageKey, 'Hello from Vue 3!');
</script>
3. Consume the Message in Child Components:
JavaScript
<script setup>
import { inject } from 'vue';
const message = inject(messageKey);
console.log(message); // Output: Hello from Vue 3!
</script>
inject
.
const message = inject('message', 'Default message');
Reactivity: Changes to provided data will propagate to descendant components that are injecting the same key, ensuring data consistency.
TypeScript Support: TypeScript provides type annotations for provide
and inject
, enhancing type safety and code clarity.
By utilizing provide
and inject
effectively, you can build modular, reusable, and data-driven Vue 3 applications with improved maintainability and flexibility.