我正在尝试在我的 TypeScript 编写的 Vue 组件中使用 mapState。
正如这里所建议的:How to use mapState function in typescript语法当使用vuex时?
我这样做是为了实现它:
<template>
<SomeComponent
:title="title">
</SomeComponent>
</template>
<script lang="ts">
import Vue from 'vue'
...
const MyComponentProps = Vue.extend({ })
@Component({
components: {
SomeComponent,
...
},
...mapGetters(['currentSubscription']),
...mapState({
content: (state: RootState) => state.content,
})
})
export default class MyComponent extends MyComponentProps {
content!: ContentModel
get title () {
this.content.someTitle
}
</script>
问题是我收到此错误:
“类型错误:无法读取未定义的属性(读取“someTitle”)”
当我直接从商店获取状态属性(不使用mapState)时,我没有收到任何错误:
get title () {
this.$store.state.content.someTitle
}
此外,当我使用手表时,我可以做到这一点:
title!: ''
...
@Watch('content')
onPropertyChanged (value: ContentModel) {
this.title = value.someTitle
}
但我发现这个解决方案冗长且可读性较差,在我看来它错过了整个 mapState 的想法。
我的问题是为什么直接调用商店时我没有收到错误,有没有办法让我将 mapState 与计算属性一起使用?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我发现了问题,我没有将地图嵌套在
计算中。@Component({ components: { SomeComponent, ... }, computed { // <--- This line solved it ...mapGetters(['currentSubscription']), ...mapState({ content: (state: RootState) => state.content, }) } })这样就一切正常了