vue.jsvuejs3vue-composition-apiinject

Vue 3 composition API, inject only works inside defineProps


Here's the way I create my component:

  const app = createApp({
    template: `
      <${componentName} />
    `,
  });

  app.provide('componentId', 'the component id');
  app.component(componentName, App);
  app.mount(element);

so the componentId is provided in the app creation.

Then inside my component I do:

<script setup>
...
const props = defineProps({
  componentId: {
    type: String,
    required: true,
    default: () => {
      return inject('componentId');
    },
  },
});
...
onMounted(async () => {
  console.log('props componentId', props.componentId); // the component id
  console.log('inject componentId', inject('componentId')); // undefined
});

What I don't understand is why when I use the onMounted the injected value is undefined, but using the props.componentId the value gets the correct value.

Why is that?

I tried using: inject('componentId') I expected: 'a component id' But I got: undefined


Solution

  • Have a look at the documentation of inject():

    Similar to lifecycle hook registration APIs, inject() must be called synchronously during a component's setup() phase.

    The onMounted() hook is triggered after the setup() phase, so inject() is not working.