【问题标题】:What are the types for { dispatch, commit } in vuex?vuex 中 { dispatch, commit } 的类型是什么?
【发布时间】:2018-10-26 18:25:41
【问题描述】:

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

async getUserProfile ({ dispatch, commit }: any) {}

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

【问题讨论】:

    标签: javascript vue.js vuejs2 flowtype vuex


    【解决方案1】:

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

    getUserProfile( context: ActionContext<S, R>) {}
    

    其中SStateRRootState

    然后你调用 dispatchcommit 离开上下文:

     context.dispatch('action')
     context.commit('mutation')
    

    【讨论】:

    • 有什么文档可以参考吗?
    【解决方案2】:

    您可以在此文件中查看可用的 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;
    }
    
    

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

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

    希望有帮助:)

    【讨论】:

      【解决方案3】:

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

      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);
          },
      };
      

      【讨论】:

      • ActionContext 签名是ActionContext&lt;S, R&gt; 这意味着第一个参数是模块状态,第二个是根状态
      【解决方案4】:

      你可以只从 vuex 导入 Commit 类型。

      import { Commit } from "vuex";
      

      并在这样的操作中使用:

      changeNumber({ commit }: { commit: Commit }, new_number: number) {
        commit("setNewNumber", new_number);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 2021-04-04
        • 2020-08-21
        • 2021-07-30
        • 1970-01-01
        • 2017-12-21
        • 2013-01-04
        相关资源
        最近更新 更多