使用Typescript注入Vue3
我使用了新的 Vue 3 Composition API 并为响应式数据编写了一个“存储”。
const state = reactive<State>({
accessToken: undefined,
user: undefined,
});
export default {
state: readonly(state),
}
在创建应用程序时,我向所有组件提供商店:
const app = createApp(App)
.provide("store", store)
.use(IonicVue)
.use(router);
最后在一个组件/视图中,我注入了 store 来使用它。
export default defineComponent({
name: "Home",
inject: ["store"],
components: {
IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
IonButton,
},
computed: {
email() {
return this.store.state.user.email;
},
},
});
</script>
不幸的是,Typescript 不喜欢我this.store在计算属性中使用的方式email()
并说
类型“ComponentPublicInstance<{}、{}、{}、{ email(): any;”上不存在属性“store”;}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, { email(): any; }、{}、ComponentOptionsMixin、ComponentOptionsMixin、EmitsOptions、字符串、{}>>'
我的意思是一切正常,当我删除lang="ts"的<script/>标签,但没有显示错误。关于如何解决这个问题或它特别意味着什么的任何建议?
提前致谢!
回答
我建议使用 store 作为全局属性而不inject在任何子组件中指定 the ,因为提供/注入可能有一些反应性警告:
const app = createApp(App)
.use(IonicVue)
.use(router);
app.config.globalProperties.store= store;
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
store:any // replace it with the right type
}
}
然后直接使用它:
export default defineComponent({
name: "Home",
components: {
...
},
computed: {
email() {
return this.store.state.user.email;
},
},
});
</script>