Skip to content

Vue Composition API: Vuex Actions and Getters

Mike Lyttle edited this page May 10, 2023 · 3 revisions

Class Component

import { Action, Getter } from "vuex-class";
    @Action("setTooManyRequestsWarning", { namespace: "errorBanner" })
    setTooManyRequestsWarning!: (params: { key: string }) => void;
    
    @Getter("isValidIdentityProvider", { namespace: "user" })
    isValidIdentityProvider!: boolean;

Composition API

import { computed } from "vue";

import container from "@/plugins/container";
import { STORE_IDENTIFIER } from "@/plugins/inversify";
import { IStoreProvider } from "@/services/interfaces";
const storeProvider = container.get<IStoreProvider>(STORE_IDENTIFIER.StoreProvider);
const store = storeProvider.getStore();
const isValidIdentityProvider = computed<boolean>(() => store.getters["user/isValidIdentityProvider"]);

function setTooManyRequestsWarning(params: { key: string }): void {
    store.dispatch("errorBanner/setTooManyRequestsWarning", params);
}

Notes

  • The signatures for the action functions can be simplified, though this will require updating the callers to match.

    function setTooManyRequestsWarning(key: string): void {
        store.dispatch("errorBanner/setTooManyRequestsWarning", { key });
    }
  • If an action is only called once, the action function can be refactored away and store.dispatch can be called directly.

  • After migrating to Vue 3 and Vuex 4, useStore() will be available to simplify retrieval of the store.

    import { computed } from "vue";
    import { useStore } from "vuex";
    const store = useStore();
  • After the migration, it will also be possible to supply correct typings for the store.

Documentation

Clone this wiki locally