【问题标题】:Implementing dependency injection using Vue and Typescript使用 Vue 和 Typescript 实现依赖注入
【发布时间】:2019-10-09 21:50:25
【问题描述】:

我尝试使用 vue-injector,但它可以使用我的 Vue (2.6.10) 和 Typescript (3.4.5) 版本进行编译。

我看到的其他选择很少。

在纯 typescript 方面,我看到 Inversify 和 TSyringe 之类的东西看起来不错,但不适用于开箱即用的 Vue。

这是反转:

Argument of type typeof App' is not assignable to parameter of type 'VueClass<Vue>'.
      Type 'typeof App' is not assignable to type 'VueConstructor<Vue>'.
        Types of parameters 'authService' and 'options' are incompatible.
          Type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<string, any>>' is missing the following properties from type 'AuthService': app, scopes, login, logout, getAccount
export default class App extends Vue {
  constructor(
    @inject(AuthService) authService: AuthService
  ) {
    super();
  }
}

我假设我需要创建一个具有正确签名的类,但在我消失在那个兔子洞之前,是否有人对 Vue/Typescript/DI 有任何经验并且可以为我指出一个明智的解决方案的方向?

【问题讨论】:

    标签: typescript vue.js dependency-injection vuejs2


    【解决方案1】:

    你可以试试这个vue-injector

    【讨论】:

      【解决方案2】:

      inject 等装饰器不能与组件类一起使用。装饰器的使用假设类由 Inversify 注入器实例化,而组件类由 Vue 框架实例化,因此提供给组件构造函数的参数不会是 AuthService 的实例。这就是类型错误的警告。

      同样的问题适用于 React 组件或任何其他内部不使用 Inversify 的框架。

      应手动访问 Inversify 容器:

      authService: AuthService = container.get(AuthService)
      

      由于Vue already provides DI,使用自己的DI可能会更方便,而不是像Inversify这样的第三方库。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2022-10-09
      • 2012-02-06
      相关资源
      最近更新 更多