mapState with TypeScript forces me to use watch on Vue component state property
P粉633733146
P粉633733146 2024-03-30 23:46:45
0
1
432

I'm trying to use mapState in my Vue component written in TypeScript. As suggested here: How to use mapState function in typescript syntax when using vuex? I did this to make it happen:

<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>

The problem is that I get this error:

"TypeError: Cannot read property of undefined (read 'someTitle')"

When I get the state property directly from the store (without using mapState), I don't get any errors:

get title () {
  this.$store.state.content.someTitle
}

Also when I use the watch I can do this:

title!: ''
...

@Watch('content')
onPropertyChanged (value: ContentModel) {
  this.title = value.someTitle
}

But I find this solution verbose and less readable, and in my opinion it misses the whole mapState idea. My question is why I don't get an error when calling the store directly, is there a way for me to use mapState with a computed property?

P粉633733146
P粉633733146

reply all(1)
P粉976488015

I found the problem, I didn't nest the map inside the calculation.

@Component({
  components: {
    SomeComponent,
    ...
  },
  computed { // <--- This line solved it
    ...mapGetters(['currentSubscription']),
    ...mapState({
      content: (state: RootState) => state.content,
    })
  }
})

This way everything will be normal

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!