我使用了新的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);
最后,在组件/视图中,我注入了商店以使用它。
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()
并说
属性'store'在类型'ComponentPublicInstance <{},{},{},{email()上不存在:any; },{},EmitsOptions,{},{},false,ComponentOptionsBase <{},{},{},{email():任意;},{},ComponentOptionsMixin,ComponentOptionsMixin,EmitsOptions,字符串,{} >>'
我的意思是一切正常,当我删除lang="ts"
的<script/>
标签,但没有显示错误。关于如何解决此问题或它的特殊含义的任何建议?
提前致谢!
我建议在没有指定inject
子组件的情况下将store用作全局属性,因为provide / inject可能会引起一些反应性警告:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句