ウェブサイト検索

javascript - vuex-class: Vueコンポーネントの外でVuexにアクセスする


vuex-class を使って、Vue コンポーネントの外で Vuex にアクセスするにはどうすればよいですか?

通常の状況では、それはかなり簡単です:

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

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

しかし、私は vuex-class を使っていて、Vuex モジュールがあります:

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

Vueコンポーネントから、私はこのようにストアのミューテーションにアクセスできます:

<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>

Vueコンポーネントの外で、TSを使ってvuex-classでMutationにアクセスするにはどうすればいいですか?

回答 #1

vuex-class を使っている場合でも、従来の方法でミューテーションを使うことができます:

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

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

あるいは、直接型指定されたミューテーションを使いたい場合は:

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

MUTATION_NAME(state, payload);

関連記事