7

When I use provide/inject with class components everything works as expected. But when I use it in a "normal" vue component I get type-errors.

In this example I get errors when referencing this.testService. The code works though.

export default Vue.extend({
  name: "HelloWorldBasic" as string,
  inject: ["testService"],

  computed: {
    message(): string | null {
      return this.testService ? this.testService.hello() : null;
    }
  }
});

Where did I make my mistake? How should I write the code?

I set up a small project to be able to reproduce it and work with it:

$ git clone [email protected]:schnetzi/vue-provide-inject.git
$ npm ci
$ npm start
3
  • hello, any news on this one?
    – A.I.S
    Mar 4, 2020 at 10:57
  • I didn't find any solution for the problem so far :/
    – schnetzi
    Apr 24, 2020 at 15:47
  • Did you ever solved it @schnetzi? If yes, how?
    – codedge
    Oct 20, 2020 at 17:56

2 Answers 2

6

This is a bit tricky to do, but it is possible using the same workaround that is commonly used for mixins, which entails defining an interface for whatever you want to add to the Vue instance.

In your case, here's how it would be done:

import Vue_ from 'vue';
import MyTestServiceType from 'wherever/it/is';

interface HelloWorldBasicInjected {
  testService: MyTestServiceType
}

const Vue = Vue_ as VueConstructor<Vue_ & HelloWorldBasicInjected>
export default Vue.extend({
  name: "HelloWorldBasic" as string,
  inject: ["testService"],

  computed: {
    message(): string | null {
      return this.testService ? this.testService.hello() : null;
    }
  }
});
1
  • Would there be a way to use this solution with using export default defineComponent({}) (SFCs)? And without using the composition API?
    – advaiyalad
    Feb 26, 2021 at 22:07
1

An alternative to the inject attribute is to use the inject() method

  import { inject } from 'vue';

  // (...)

  data() {
    return {
      testService: inject('testService') as TestService,
    };
  },

After which you can use this.testService as you did: this.testService?.hello()

inject() can even take a default value as second parameter in case the injection isn't resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.