【问题标题】:vuex + typescript + namespace modules: accessing other module statevuex + typescript + 命名空间模块:访问其他模块状态
【发布时间】:2019-03-22 15:52:00
【问题描述】:

我正在使用带有 typescript 和命名空间模块的 vuex。 我有 2 个模块:“UserProfile”和“Trips”。 一切都在一个模块中运行。

我需要从“Trip”模块的一个动作中访问存储在“UserProfile”模块状态中的当前用户。

据我所知,如果我不使用 typecirpt,我可以使用 rootState["profile/user"]。

但是对于打字稿,编译器会给我这样的错误:

Element implicitly has an 'any' type because type 'RootState' has no index signature.

这是我在“旅行”模块中的操作:

async createTrip({ commit, state, rootState, rootGetters}) {
    const user = rootState["profile/user"];
}

有人知道在使用 vuex + typescript 时访问另一个命名空间模块拥有的状态的正确方法吗?

谢谢。

===== 更新 =====

目前,我找到的唯一可行的解​​决方案是:

1] 为每个模块创建一个返回其整个状态的 getter(即“Profile”模块添加一个返回 ProfileState 类型的 getter)

2] 通过 rootGetters 从另一个模块使用该 getter,如下所示:

 async createTrip({ commit, state, rootState, rootGetters}) {
    const profileState: ProfileState= rootGetters["profile/getState"];
    if(profileState.user === undefined ) return;
    console.log("CurrentUser: " + profileState.user.uid);
}

【问题讨论】:

    标签: typescript vue.js vuex


    【解决方案1】:

    但是对于打字稿,编译器会给我这样的错误:

    Element implicitly has an 'any' type because type 'RootState' has no index signature.

    此错误表明您在类型声明中错过了添加定义:

    例如:

    export type RootState = {
      //...
      profile?: ProfileState
    }
    

    或

    export type RootState = {
      //...
      [k in keyof ModuleStateTypes]?: ModuleStateTypes[k] 
    }
    

    Mapped types

    【讨论】:

      【解决方案2】:

      只是一个想法,不能简单地将这些模块添加到 rootState typedef 中吗? 像这样:

      { ...; moduleName?: moduleState;}
      

      甚至:

      { ...; [key: string | number]: any;}
      

      【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 2018-12-31
      • 2021-08-27
      • 1970-01-01
      • 2018-10-29
      • 2017-05-12
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多