当我使用 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/