vue.js - 如何使用提供/注入 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
解决方案
这有点棘手,但可以使用通常用于 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;
}
}
});
推荐阅读
- ios - Swift:在 tableView 中搜索 JSON 数据
- android - 从 API 27 弃用 FragmentStatePagerAdapter
- jquery - 在html中以表格格式检索xml数据
- php - 如果引荐来源网址不匹配,则有条件重定向 WordPress
- javascript - 使用 new Map() 映射单个键多个值 - javascript
- java - 响应式字体大小 Java
- recursion - SUCC 的功能
- angular - 角度模态错误: ariaLabelledBy 在 NgbModalOptions 中不存在
- fortran - 从不同的 fortran 代码中读取变量
- wordpress - 插件更新时主题设置重置为默认值