Skip to content

Vue Composition API: Vuex Actions and Getters

Mike Lyttle edited this page May 12, 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 { useStore } from "vue-composition-wrapper";
const store = useStore();
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, the "vue-composition-wrapper" package can be removed and useStore can be imported from "vuex".

    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