请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

关于 Vuex 结合 TypeScript 编写分模块的 Store 时类型定义的问题

在 Vuex 中使用 TypeScript,并使用 Module 将 Vuex 分为多个模块:

// src/store/index.ts
import { createStore } from 'vuex';

// Modules
import login from '@/pages/Login/store';

export interface RootState {
  temp: string;
}

const state: RootState = {
  temp: '',
};

export default createStore<RootState>({
  state,
  mutations: {},
  actions: {},
  modules: { login },
});
// src/pages/Login/store
import { Module } from 'vuex';

// Store
import mutations from './mutations';
import actions from './actions';
import getters from './getters';

// Types
import { RootState } from '@/store';

export interface State {
  activeTab: 'login' | 'register';
}

const state: State = {
  activeTab: 'login',
};

const module: Module<State, RootState> = {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};

export default module;

error

使用这种方式定义后,在代码中取 store.state.login.activeTab 会标红报错,请问老师有没有比较优雅的解决办法,网上搜了一圈都没看到比较优雅的方式。

正在回答 回答被采纳积分+3

1回答

张轩 2021-04-11 06:39:15

同学你好 将你的 login 的 state 导出,在 RootState 中定义即可,注意在根store createStore的时候不要传泛型进去。

export interface GlobalDataProps {
    user: UserProps;
    templates: TemplatesProps;
    editor: EditorProps;
    global: GlobalStatus;
}
const store = createStore({
    modules: {
        user,
        templates,
        editor,
        global
    }
})

创建的时候使用 useStore<GlobalDataProps>()

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号