我使用了新的Vue 3组合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>不幸的是,类型记录不喜欢,就像我在computed property email()中使用this.store那样
并说
属性'ComponentPublicInstance<{},{ email():any;},{},EmitsOptions,{},{},false,ComponentOptionsBase<{},{ email():any;},{},ComponentOptionsMixin,ComponentOptionsMixin,EmitsOptions,string,{}>>‘
我的意思是,当我删除lang="ts"标记中的<script/>时,一切都正常,但是没有显示错误。对于如何解决这个问题,或者它特别意味着什么,有什么建议吗?
提前感谢!
发布于 2021-01-14 10:20:54
我建议将存储作为全局属性使用,而无需在任何子组件中指定inject,因为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>发布于 2021-10-31 22:39:31
对于那些使用Vue 3+ TS处理相同问题的人,我找到了一个解决方案,无需更改app.config或声明一个新的module
import { createApp, reactive } from 'vue'
import App from './App.vue'
const Store = reactive({
myProperty: 'my value'
})
createApp(App)
.provide('Store', Store)
.mount('#app')<template>
<div>{{ Store.myProperty }}</div>
</template>
<script lang="ts">
import { IStore } from '@/types'
import { defineComponent, inject } from 'vue'
export default defineComponent({
name: 'MyComponentName',
setup() {
return {
Store: inject('Store') as IStore,
}
},
created() {
console.log(this.Store) // will show the `Store` in the console
}
})
</script>@/types.ts)的类型指示:export interface IStore {
myProperty: string
}按照以下三个步骤,我能够在使用Store.myProperty时不出问题地读写TypeScript
https://stackoverflow.com/questions/65716936
复制相似问题