gpt4 book ai didi

api - TypeScript 编译器在 Vue 对象组件中找不到注入(inject)的属性

转载 作者:行者123 更新时间:2023-12-05 08:08:27 26 4
gpt4 key购买 nike

我正在为工作编写几个示例,其中一个让我挂掉的是注入(inject) Vue 引导期间提供的服务。

这个“有效”(我可以访问它,它编译并运行),我的 JavaScript 版本和 Class-Component TypeScript 版本都没有问题或提示,但编译器提示 this.sampleService 当使用带有 TypeScript 的 Vue 对象 API 时,我的组件中不存在。

我错过了什么吗?

<template>
<div class="app">
{{message}} <fake-button :text="buttonText" @some-click-event="handleClickEvent"></fake-button>
</div>
</template>

<style lang="scss">
.app {
$background-color: #9f9;
$foreground-color: #000;
background: $background-color;
color: $foreground-color;
}
</style>

<script lang="ts">
import Vue from 'vue'

const App = Vue.extend({
components: {
FakeButton: () => import('@client/components/fake-button/fake-button-object-typescript.vue')
},
data: function () {
return {
message: 'Hello World - App Object TypeScript',
buttonText: 'Click Me'
}
},
inject: {
sampleService: 'sampleService'
},
methods: {
handleClickEvent(someVal?: string) {
console.log('App', 'handleClickEvent', someVal);
}
},
beforeCreate() {
console.log('App', 'beforeCreate');
},
created() {
console.log('App', 'created');
},
mounted() {
console.log('App', 'mounted');
// TODO: While this compiles, TypeScript complains that it doesn't exist
console.log('this.sampleService.getDate()', this.sampleService.getDate());
}
});

export default App;
</script>

ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts
[tsl] ERROR in vue-test/src/client/containers/app/app-object-typescript.vue.ts(35,56)
TS2339: Property 'sampleService' does not exist on type 'CombinedVueInstance<Vue, { message: string; buttonText: string; }, { handleClickEvent(someVal?: s...'.

最佳答案

我对这个问题的解决方案是为注入(inject)创建一个接口(interface)。在您的示例中,这将类似于以下内容:

<script lang="ts">
import { SampleServiceInjection } from '...';

const App = ( Vue as VueConstructor<Vue & SampleServiceInjection> ).extend({
inject: {
sampleService: 'sampleService'
} as Record<keyof SampleServiceInjection, string>,
// etc.
});
</script>

您也可以在提供服务的组件中使用该接口(interface):

export interface SampleServiceInjection {
sampleService: SampleService; // or whatever type your service has
}

export default Vue.extend({
provide(): SampleServiceInjection {
return {
sampleService: new SampleService(),
};
},
// etc.
});

关于api - TypeScript 编译器在 Vue 对象组件中找不到注入(inject)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49931226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com