4

How can I get access to Vuex outside of a Vue component with vuex-class?

In normal situation it is pretty simple:

// some JS file
import store from './../store'; // path to Vuex store

store.commit('ux/mutationName', somePayload)

But I am using vuex-class and I have Vuex module:

import { Module } from 'vuex';
import { RootState } from '@/types/vuex/types';
import { MutationTree } from 'vuex';
import { GetterTree } from 'vuex';

const namespaced: boolean = true;

export interface UXState {
  compLoading: boolean;
}

export const state: UXState = {
  compLoading: false
};

export const mutations: MutationTree<UXState> = {
  setCompLoading(state, payload: boolean): void {
    state.compLoading = payload;
  }
};

export const getters: GetterTree<UXState, RootState> = {
  compLoading(state): boolean {
    return state.compLoading;
  }
};

export const ux: Module<UXState, RootState> = {
  namespaced,
  state,
  mutations,
  getters
};

Fom Vue component I have access to store Mutations in this way:

<script lang="ts">
  import axios from 'axios';
  import {Component, Vue} from 'vue-property-decorator';
  import {Mutation} from "vuex-class";
  const namespace: string = "ux";

  @Component({
    name: 'CompName'
  })
  export default class AppNavigationBar extends Vue {

    @Mutation('setCompLoading', { namespace })
    setCompLoading!: (flag: boolean) => void;

    async created() {
      this.setCompLoading(true);
      const resp = await axios.get('someURL');
      this.setCompLoading(false);
    }
  }
</script>

How can I get access to Mutation using vuex-class with TS outside of a Vue component?

1 Answer 1

6

Even though you are using vuex-class, you can still use mutations the old way:

import store from './../store';

store.commit('module/mutationName', payload);

Or, if you prefer to use the typed mutation directly:

import state from './../store/state';
import { MUTATION_NAME } from  './../store/mutations'; // Or wherever you have them

MUTATION_NAME(state, payload);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.