Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading