【问题标题】:How to use provide/inject with TypeScript but without vue-class-component如何使用提供/注入 TypeScript 但没有 vue-class-component
【发布时间】:2020-02-25 01:11:55
【问题描述】:

当我将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

【问题讨论】:

  • 你好,这个有消息吗?
  • 到目前为止我没有找到任何解决问题的方法:/
  • 你有没有解决它@schnetzi?如果是,怎么做?

标签: vue.js vue-component


【解决方案1】:

这有点棘手,但可以使用与 commonly used for 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;
    }
  }
});

【讨论】:

  • 有没有办法通过export default defineComponent({}) (SFC) 使用这个解决方案?并且不使用组合 API?
【解决方案2】:

inject 属性的替代方法是使用inject() 方法

  import { inject } from 'vue';

  // (...)

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

之后您可以像以前一样使用this.testServicethis.testService?.hello()

inject() 甚至可以将默认值作为第二个参数,以防注入未解决。

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 2022-06-16
    • 1970-01-01
    • 2018-04-06
    • 2020-03-30
    • 2018-04-06
    • 2021-04-19
    • 2021-10-27
    • 2021-03-17
    相关资源
    最近更新 更多