【问题标题】:Vuex - TypeScript mapGettersVuex - TypeScript mapGetters
【发布时间】:2020-06-22 18:09:43
【问题描述】:

我无法理解 mapGetters 如何使用 TypeScript。我正在关注示例here,但无法使用建议使其工作

这是我的代码

getters.ts

export const GET_POSTS = 'GET_POSTS'

posts.module

import {GET_POSTS} from '../types/getters'
...
  get [GET_POSTS]() {
    return this.posts || [];
  }

PostsList.vue

@Component({
  components: { PostListItem },
  computed: mapGetters(["GET_POSTS"]) // what local prop does this map to or how do I access it?
})
export default class PostsList extends Vue {
  name = "PostsList";
  posts = [];

  /**
   * Get posts
   */
  async mounted() {
   console.log(this.GET_POSTS); // ERROR: Property 'GET_POSTS' does not exist on type 'PostsList'.
  }

基本上,我正在尝试做:

...mapGetters({
   posts: GET_POSTS
})

console.log(this.posts)

【问题讨论】:

    标签: typescript vue.js vuex


    【解决方案1】:

    提到的问题suggests the solution。由于 Vue 类组件无法推断成员的类型,因此应断言映射的 Vuex 项:

    应该是:

    GET_POSTS!: () => PostInterface[];
    posts: PostInterface[] = [];
    

    断言要求开发人员负责提供的类型。如果mapGetters(["GET_POSTS"]) 丢失或不符合预期提供的类型,这将导致运行时错误。

    Vue 类组件预计将被弃用。 Composition API 为 TypeScript 提供了更好的支持。

    【讨论】:

      猜你喜欢
      • 2018-07-07
      • 2020-06-17
      • 2018-01-08
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多