Vue3 inject() Function
inject()The inject() function is an API provided by Vue3, used in child components to obtain dependencies provided by parent or ancestor components throughprovide()the provide() function. It is mainly used for data transfer between cross-level components, especially when the component tree is deep.
Basic Syntax
Example
import { inject } from 'vue';
const value = inject(key, defaultValue);
const value = inject(key, defaultValue);
- key: A string or Symbol representing the unique identifier of the dependency to be injected.
- defaultValue: Optional parameter. If the corresponding dependency is not found, the default value is returned.
Use Cases
inject()Usually used together withprovide()and is suitable for the following scenarios:
- Cross-level component communication: When the component hierarchy is deep, through
provide()andinject()it can avoid the hassle of passing props layer by layer. - Global state management: In small applications, you can use
provide()andinject()to replace state management tools such as Vuex. - Plugin development: When providing global functionality or configuration in plugins,
inject()it is a convenient tool.
Code Examples
Parent Component Uses provide() to Provide Data
Example
import { provide, ref } from 'vue';
export default {
setup() {
const message = ref('Hello, Vue3!');
provide('message', message); // Provide data
}
};
export default {
setup() {
const message = ref('Hello, Vue3!');
provide('message', message); // Provide data
}
};
Child Component Uses inject() to Get Data
Example
import { inject } from 'vue';
export default {
setup() {
const message = inject('message', 'Default Message'); // Inject data
return { message };
}
};
export default {
setup() {
const message = inject('message', 'Default Message'); // Inject data
return { message };
}
};
Notes
- Reactivity of Dependencies: If the data provided via
provide()is reactive (e.g.,reforreactive), then in child components, usinginject()to obtain the data will also remain reactive. - Role of Default Values: If the corresponding dependency is not found,
inject()the default value will be returned. It is recommended to always set a default value to avoid runtime errors. - Avoid Overuse: Although
provide()andinject()is very convenient, overuse may lead to increased coupling between components. It is recommended to use it only when necessary.
Other Extensions
Vue3 Options API