In Vue 3, the inject function is used to inject dependencies into a component. It allows child components to access values or functions provided by their parent components or a higher level in the component tree.

Here's an example of how to use the inject function in Vue 3:

Parent component:

import { createApp, provide } from 'vue';
import ChildComponent from './ChildComponent';

const app = createApp({
  setup() {
    provide('message', 'Hello from parent component!');
  },
  template: `
    <div>
      <ChildComponent />
    </div>
  `,
});

app.component('ChildComponent', ChildComponent);

app.mount('#app');

Child component:

import { inject } from 'vue';

export default {
  setup() {
    const message = inject('message');
    return { message };
  },
  template: `
    <div>
      {{ message }}
    </div>
  `,
};

In this example, the provide function is used in the parent component to provide the 'message' dependency to its child components. The inject function is then used in the child component to retrieve the 'message' value and make it available in the component's template.

Note that the provide and inject functions in Vue 3 are part of the new Composition API, which provides a more flexible and powerful way to structure and reuse code in Vue components

vue3 inject

原文地址: https://www.cveoy.top/t/topic/it5x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录