vue.js - 如何使用提供/注入(inject) TypeScript 但没有 vue-class-component

标签 vue.js vue-component

当我使用 provide/inject使用类组件,一切都按预期工作。但是当我在 中使用它时“正常” vue 组件 我得到 类型错误 .

在此示例中,引用 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

最佳答案

这有点棘手,但可以使用与 commonly used for mixins 相同的解决方法。 ,这需要为要添加到 Vue 实例的任何内容定义一个接口(interface)。
在您的情况下,这是如何完成的:

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

关于vue.js - 如何使用提供/注入(inject) TypeScript 但没有 vue-class-component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58613472/

相关文章:

javascript - VueJS 组件中的图像未加载

vue.js - 我可以向 Vuetify datepicker 添加自定义翻译吗?

javascript - 从 Vuex 中的数组中删除特定项目

javascript - 如何根据另一个选择值有条件地加载选择选项

vue.js - 在 v-for 中选择/取消选择单个元素

javascript - Vue.js - 无法将日期/时间选择器添加到 vue.js 渲染的 html 元素中

javascript - 在 Vue 上,如何在另一个组件中使用一个组件的函数?

vue.js - 使用新版本自动更新 Vue 站点/PWA

javascript - Vue.js $children 按组件名称

node.js - 如何使用 sails js + vue js 模板制作应用程序?