sch*_*tzi 6 vue.js vue-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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
我在哪里犯了错误?我应该怎么写代码?
我建立了一个小项目,以便能够重现它并使用它:
$ git clone git@github.com:schnetzi/vue-provide-inject.git
$ npm ci
$ npm start
Run Code Online (Sandbox Code Playgroud)
小智 6
这做起来有点棘手,但可以使用与 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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
753 次 |
| 最近记录: |