[英]mapState with TypeScript is enforcing me to use watch on my Vue component state properties
我正在尝试在我的TypeScript
ed 编写的Vue
组件中使用mapState
。 正如这里所建议的: How to use mapState function in typescript syntax when using 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>
问题是我收到此错误:
“TypeError:无法读取未定义的属性(读取‘someTitle’)”
当我直接从商店(不使用 mapState)获取 state 属性时,我没有收到任何错误:
get title () {
this.$store.state.content.someTitle
}
另外,当我使用 watch 时,我可以这样做:
title!: ''
...
@Watch('content')
onPropertyChanged (value: ContentModel) {
this.title = value.someTitle
}
但我发现这个解决方案冗长且可读性差,在我看来它错过了整个mapState
想法。 我的问题是,为什么在直接调用商店时我没有收到错误,有没有办法让我将mapState
与计算属性一起使用?
我发现了问题,我没有将地图嵌套在computed
中。
@Component({
components: {
SomeComponent,
...
},
computed { // <--- This line solved it
...mapGetters(['currentSubscription']),
...mapState({
content: (state: RootState) => state.content,
})
}
})
这样一切正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.