How to use Vuex namespaced getter with the Composition API

Viewed 1617

I am currently trying to retrieve the tags in the Searchbar module from Vuex. However, it is not reactive.

Here is the component :

<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
    };
  }
});

and the vuex module

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);
  }
}

I don't see why. I am using Typescript, and so it does not support the store.Searchbar.getters['all'])... Got an idea ?

1 Answers

Ok I found the problem. My bad : it has nothing to do with the composition API. The above code is working concerning it.

In the Vuex module, I had to update the addTag mutation as follow :

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

Basically array changes are not reactive by default, so we have to use the Vue.setmethod.

Related