vuex 4.0 + Typescript 模块的声明

·  阅读 1732
// store/index.ts

export default createStore({
  modules: {
    account,
  },
  state: {
    globalLoading: false,
  },
  // 其他代码
}
复制代码
// store/index.d.ts

// 这里的声明保持和 index.ts 文件的 state 一直
export interface RootState {
  globalLoading: boolean
}
复制代码
// store/module/account.ts

// 声明方式一
import { Module } from 'vuex'
import { RootState } from './../index.d'

interface UserInfo {
  id?: number,
  nickname?: string
}
interface AccountState {
  userInfo: UserInfo
}
interface SendCode {
  mobile: string,
}

const account: Module<AccountState, RootState> = {
  state: {
    userInfo: {},
  },
  mutations: {
    setUserInfo(state, payload: UserInfo): void {
      state.userInfo = payload
    },
  },
  actions: {
    async sendCode({ commit }, payload: SendCode): Promise<object> {
      console.log('in sendCode actions, data:', payload)
      // return await api.post('/sendCode', data)
      return Promise.resolve({})
    },
  }
}

export default account
复制代码
// store/module/account1.ts

// 声明方式二
import { GetterTree, MutationTree, ActionTree } from 'vuex'
import { RootState } from './../index.d'

interface UserInfo {
  id?: number,
  nickname?: string
}
interface AccountState {
  userInfo: UserInfo
}
interface SendCode {
  mobile: string,
}

const state: AccountState = {
  userInfo: {},
}

const getters: GetterTree<AccountState, RootState> = {
  accountId(state) {
    return state.userInfo.id
  }
}

const mutations: MutationTree<AccountState> = {
  setUserInfo(state, payload: UserInfo): void {
    state.userInfo = payload
  },
}

const actions: ActionTree<AccountState, RootState> = {
  async sendCode({ commit }, payload: SendCode): Promise<object> {
    console.log('in sendCode actions, data:', payload)
    // return await api.post('/sendCode', data)
    return Promise.resolve({})
  },
}

export default {
  state,
  getters,
  mutations,
  actions,
}
复制代码
分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改