TypeScript 在vue中定義全局類型


🚀🚀 全局類型定義 🚀🚀

  • 路徑 src/types/store.d.ts
/**
 * 定義全局的State在 store.d.ts文件中
 */

// 單獨的state,導出為單獨的module使用
export interface LoginState {
  user: object
}

// 全部的state,導出 Vuex.Store時使用
export interface RootState {
  login: LoginState
}

// 在 src/store.index.ts 下使用 RootState
export default new Vuex.Store<RootState>({
  modules: {
    login
  }
})

🚀🚀 store 下單獨的 login module => 使用類型定義中的 LoginState 🚀🚀

import { Commit } from 'vuex'

import { LoginState } from '@/types/store' // 引入 store.d.ts 下定義的 LoginState

export interface IUser { // 參數需要的類型定義
  email: string
  token: string
  username: string
  bio: string
  image: string
}

// 引入全局的
const state: LoginState = {
  user: {}
}

const mutations = {
  setUser(state: LoginState, user: IUser) {
    state.user = user
  }
}

const actions = {
  setUser(context: { state: LoginState, commit: Commit }, user: IUser) {
    context.commit('setUser', user)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

🚀🚀 總結 🚀🚀

  • src/types/store.d.ts下定義單獨 module 下的 ModuleState(LoginState)
  • 將定義的 ModuleState(LoginState) 匯總到 RootState下 供 export default new Vuex.Store<RootState> 使用
  • 定義單獨的參數類型 ParamsTypestore下的各自module下(IUser) 參照上面的demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM