TypeScript 在vue中定义全局类型
时间:2020-08-09 23:40:05
收藏:0
阅读:431
全局类型定义
- 路径
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>使用 - 定义单独的参数类型
ParamsType在store下的各自module下(IUser) 参照上面的demo
原文:https://www.cnblogs.com/leslie1943/p/13466943.html
评论(0)