vuex 中 { dispatch, commit } 的类型是什么?

pre*_*tch 6 javascript vue.js flowtype vuex vuejs2

我有 vujes 打字稿项目,在 vuex 商店我得到了类似的东西:

async getUserProfile ({ dispatch, commit }: any) {}
Run Code Online (Sandbox Code Playgroud)

好吧,我不想要,any因为那很糟糕,而且您在编辑器中没有帮助/自动完成功能。我找到了这个import { Dispatch, Commit } from "vuex";但是如何将该信息传递给{ dispatch, commit }: any

Ohg*_*why 13

你使用ActionContext<S, R>,就像 Vuex 一样:

getUserProfile( context: ActionContext<S, R>) {}
Run Code Online (Sandbox Code Playgroud)

哪里SStateRRootState

然后调用dispatchcommit关闭的背景下:

 context.dispatch('action')
 context.commit('mutation')
Run Code Online (Sandbox Code Playgroud)

  • 有什么文档可以参考吗? (3认同)

小智 6

您可以在此文件中查看可用的 vuex 类型:

node_modules/vuex/types/index.d.ts

// 第 49 行:

export interface Commit {
  (type: string, payload?: any, options?: CommitOptions): void;
  <P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}

Run Code Online (Sandbox Code Playgroud)

您可以像这样导入和使用它而不是 ActionContext:

import { Commit } from 'vuex';

const actions = {
    loadUser ({ commit }: { commit: Commit }, user: any) {
        commit('setUser', user);
    },

    ...
};
Run Code Online (Sandbox Code Playgroud)

希望有帮助:)


小智 5

如果您愿意,您仍然可以解构上下文对象。

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

  • ActionContext 签名是 `ActionContext&lt;S, R&gt;`,这意味着第一个参数是模块状态,第二个参数是根状态 (2认同)