最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What are the types for { dispatch, commit } in vuex? - Stack Overflow

programmeradmin1浏览0评论

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

Share Improve this question edited May 16, 2018 at 22:11 Emile Bergeron 17.4k5 gold badges84 silver badges131 bronze badges asked May 16, 2018 at 15:54 pregmatchpregmatch 2,6476 gold badges35 silver badges72 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 20

You 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);
}
发布评论

评论列表(0)

  1. 暂无评论