如何使用vuex类在Vue组件之外访问Vuex?
通常情况下很简单:
// some JS file
import store from './../store'; // path to Vuex store
store.commit('ux/mutationName', somePayload)
但是我正在使用vuex类,并且具有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
};
Fom 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类访问Mutation?
答案 0 :(得分:1)
即使您使用的是vuex类,仍然可以按旧方式使用突变:
blob.service_url_for_direct_upload
或者,如果您希望直接使用类型化的突变:
import store from './../store';
store.commit('module/mutationName', payload);