首页 > 解决方案 > 如何使用提供/注入 TypeScript 但没有 vue-class-component

问题描述

当我使用provide/inject类组件时,一切都按预期工作。但是当我在“普通” vue 组件中使用它时,我得到type-errors

在此示例中,我在引用this.testService. 代码虽然有效。

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

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

我在哪里犯了错误?我应该如何编写代码?

我建立了一个小项目,以便能够重现它并使用它:

$ git clone git@github.com:schnetzi/vue-provide-inject.git
$ npm ci
$ npm start

标签: vue.jsvue-component

解决方案


这有点棘手,但可以使用通常用于 mixins的相同解决方法,这需要为要添加到 Vue 实例的任何内容定义一个接口。

在您的情况下,这是如何完成的:

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

推荐阅读