vuex使用命名空间模块化后如何使得store具备类型?
来源:6-11 Vuex 整合当前应用
			ForCoke
2022-05-02
老师,我用vuex时候,使用了模块化:
user.ts
export interface UserProps{
  isLogin: boolean;
  name?: string;
  id?: number;
}
const user: UserProps = {
  isLogin: false
}
export const userStore = {
  namespace: true,
  state: () => user
}
column.ts
import { testData, testPosts } from '../testData'
export default {
  namespace: true,
  state: () => ({
    columns: testData,
    posts: testPosts
  })
}
index.ts
import { createStore } from 'vuex'
import columnStore from './column'
import { userStore, UserProps } from './user'
import { ColumnProps, PostProps } from '../testData'
// export interface GlobalDataProps {
//   columns: ColumnProps[];
//   posts: PostProps[];
//   user: UserProps;
// }
export interface GlobalDataProps {
  userStore: UserProps
}
export default createStore<GlobalDataProps>({
  modules: {
    columnStore,
    userStore
  }
})
// export default createStore({
//   modules: {
//     columnStore,
//     userStore
//   }
// })
此时通过createStore创建出来的store可以正常的使用,即:store.state.userStore.isLogin
但是,我想要请教一下老师,在这种模块化下,我如何使得我通过createStore创建出来的store实例具有相应的类型?也就是如何使得我的modules甚至我嵌套的modules也能具备类型?
写回答
	1回答
- 
				
						张轩
2022-05-03
同学你好
可以这样,
// 导出这个对应的类型,只给 createStore 的时候当泛型使用 export interface GlobalDataProps { columns: ColumnProps[]; posts: PostProps[]; user: UserProps; } // 创建 store 的时候就不需要传入 类型了 const store = createStore({ modules: { user, columns, posts, } }) // 使用的时候,就用这个 interface const store = useStore<GlobalDataProps>() // 现在 store 已经可以获取不同的类型了022022-05-04 
相似问题