vuex-class:在 Vue 组件之外访问 Vuex

Sta*_*lav 4 javascript typescript vue.js vuex

如何使用 vuex-class 在 Vue 组件之外访问 Vuex?

在正常情况下,这非常简单:

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

store.commit('ux/mutationName', somePayload)
Run Code Online (Sandbox Code Playgroud)

但我正在使用 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
};
Run Code Online (Sandbox Code Playgroud)

Fom Vue 组件我可以通过这种方式存储 Mutations:

<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>
Run Code Online (Sandbox Code Playgroud)

如何在 Vue 组件之外使用带有 TS 的 vuex-class 来访问 Mutation?

小智 6

即使您使用的是 vuex-class,您仍然可以按照旧的方式使用突变:

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

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

Run Code Online (Sandbox Code Playgroud)

或者,如果您更喜欢直接使用类型化突变:

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

MUTATION_NAME(state, payload);
Run Code Online (Sandbox Code Playgroud)