I got vujes typescript project and in vuex store i got something like:
async getUserProfile ({ dispatch, commit }: any) {}
Well i dont want any
because that suck and you dont have help/autocomplete in editor. I found this import { Dispatch, Commit } from "vuex";
but how to pass that info to { dispatch, commit }: any
I got vujes typescript project and in vuex store i got something like:
async getUserProfile ({ dispatch, commit }: any) {}
Well i dont want any
because that suck and you dont have help/autocomplete in editor. I found this import { Dispatch, Commit } from "vuex";
but how to pass that info to { dispatch, commit }: any
4 Answers
Reset to default 20You use ActionContext<S, R>
, like Vuex does:
getUserProfile( context: ActionContext<S, R>) {}
Where S
is the State
and R
is the RootState
.
Then you call dispatch
and commit
off of the context:
context.dispatch('action')
context.commit('mutation')
You can check out available vuex types in this file:
node_modules/vuex/types/index.d.ts
// line 49 :
export interface Commit {
(type: string, payload?: any, options?: CommitOptions): void;
<P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}
you can import and use that instead of ActionContext like so:
import { Commit } from 'vuex';
const actions = {
loadUser ({ commit }: { commit: Commit }, user: any) {
commit('setUser', user);
},
...
};
hope that helps :)
You can still destructure the context object if you'd like.
import { ActionContext } from 'vuex';
import { RootState } from './types';
const actions = {
// destructured
loadUser ({ commit }: ActionContext<RootState, RootState>, user: any) {
commit('setUser', user);
},
// not destructured
loadUser (context: ActionContext<RootState, RootState>, user: any) {
context.commit('setUser', user);
},
};
You can just import Commit type from vuex.
import { Commit } from "vuex";
and use in actions like this:
changeNumber({ commit }: { commit: Commit }, new_number: number) {
commit("setNewNumber", new_number);
}