Vue3 inject() Function


Vue3 选项式 APIVue3 Options API

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);
  • 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:

  1. Cross-level component communication: When the component hierarchy is deep, throughprovide()andinject()it can avoid the hassle of passing props layer by layer.
  2. Global state management: In small applications, you can useprovide()andinject()to replace state management tools such as Vuex.
  3. 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
  }
};

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 };
  }
};

Notes

  1. Reactivity of Dependencies: If the data provided viaprovide()is reactive (e.g.,reforreactive), then in child components, usinginject()to obtain the data will also remain reactive.
  2. 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.
  3. Avoid Overuse: Althoughprovide()andinject()is very convenient, overuse may lead to increased coupling between components. It is recommended to use it only when necessary.

Vue3 选项式 APIVue3 Options API

Other Extensions