簡體   English   中英

vuex + Typescript +名稱空間模塊:訪問其他模塊狀態

[英]vuex + typescript + namespace modules: accessing other module state

我正在將vuex與typescript和命名空間模塊一起使用。 我有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 +打字稿時,有人知道訪問另一個命名空間模塊擁有的狀態的正確方法嗎?

謝謝。

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

目前,我發現的唯一可行的解​​決方案是:

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

只是一個想法,不能簡單地在rootState typedef中添加這些模塊嗎? 像這樣:

{ ...; moduleName?: moduleState;}

甚至:

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

但是使用打字稿,編譯器給我這樣的錯誤:

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] 
}

映射類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM