【问题标题】:How to use Vuex namespaced getter with the Composition API如何将 Vuex 命名空间的 getter 与 Composition API 一起使用
【发布时间】:2020-06-04 13:46:24
【问题描述】:

我目前正在尝试从 Vuex 检索 Searchbar 模块中的 tags。但是,它不是反应式的。

这是组件:

<template>
  <div class="tags">
    <tag v-for="tag in tags" :key="tag.name">{{ tag.name }}</tag>
  </div>
</template>
import { defineComponent, computed } from '@vue/composition-api';
import store from '@/store/index';
import Tag from '@/components/BaseTag.vue';

export default defineComponent({
  components: {
    Tag
  },
  setup() {
    const tags = computed(() => store.getters['Searchbar/all']);
    return {
      tags
    };
  }
});

和 vuex 模块

import { Module, VuexModule, Mutation } from 'vuex-module-decorators';
import { TagType } from '@/enums';

type VuexTag = { name: string; type: TagType };

@Module({
  namespaced: true
})
export default class Searchbar extends VuexModule {
  private tagsInput: Array<VuexTag> = [];

  get all(): Array<VuexTag> {
    return this.tagsInput;
  }

  @Mutation
  addTag(tag: VuexTag): void {
    this.tagsInput[this.tagsInput.length] = tag;
  }

  @Mutation
  removeTag(index: number): void {
    this.tagsInput.splice(index, 1);
  }
}

我不明白为什么。我正在使用 Typescript,因此它不支持 store.Searchbar.getters['all'])... 有想法吗?

【问题讨论】:

  • 你的 VuexModule 是什么样子的?
  • 包装器应该推断出你正在访问的属性的类型(getter、mutation、action),所以尝试这样做:store.getters.myModule.myGetter; store.commit.myModule.myMutation(myPayload);
  • @AndreForonda 返回:Error in render: "TypeError: _store_index__WEBPACK_IMPORTED_MODULE_2__.default.getters.Searchbar is undefined"。 store.commit('Searchbar/addTag', { name: 'randomTag', type: TagType.NORMAL }); 正在按预期工作。

标签: vue.js vuex vue-composition-api


【解决方案1】:

好的,我发现了问题。我的不好:它与组合 API 无关。上面的代码正在处理它。

在 Vuex 模块中,我必须更新 addTag 突变如下:

  @Mutation
  addTag(tag: SearchbarTag): void {
    Vue.set(this.tagsInput, this.tagsInput.length, tag);
  }

默认情况下,数组更改基本上不是反应式的,因此我们必须使用Vue.set方法。

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2020-06-27
    • 2012-01-11
    • 2016-09-14
    • 2021-08-26
    相关资源
    最近更新 更多