Vuex TypeScript - ChoDragon9/posts GitHub Wiki
Vuex๋ ์ด๋ฒคํธ ๊ธฐ๋ฐ API๋ก ์ ์์ธก๊ณผ ์ฌ์ฉ์ธก์ด ๋ฃจ์ฆํ๊ฒ ์ฐ๊ฒฐ๋์ด ์๋ค. ์ด๋ฒคํธ ๊ธฐ๋ฐ API์์ ๋น๋กฏ๋๋ ์ค๋ฅ๊ฐ ๋ช๊ฐ์ง ์๋ค.
1. ์ก์
๊ณผ ๋ฎคํ
์ด์
์ฌ์ฉ ์, ์ฌ์ฉ์ธก์์ ์ ์์ ์ผ๋ก ์ ์๋์๋ ์ง ๋ฐํ์์ ํตํด์๋ง ์ ์ ์๋ค.
2. ์์๋ฅผ ํตํด ์ ์์ธก๊ณผ ์ฌ์ฉ์ธก์ ์ผ์น์์ผ๋ ํด๋น ๋ชจ๋๊ณผ ์ผ์นํ์ง ์๋ ์ก์
์ฌ์ฉ์, ๋ฐํ์์ ํตํด์๋ง ์ ์ ์๋ค.
๊ฒฐ๊ตญ ๋ฐํ์์ ํตํด์๋ง ์ ์๋์์ ํ์ธํ ์ ์๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์ฌ๊ธฐ์๋ ์ปดํ์ผํ์์์ ์ ์์ ์ผ๋ก ๋์ํจ์ ์ ์ ์๊ฒ ํ์ ์ ์ถ๊ฐํ๋ค.
import { Dispatch, Mutation, CommitOptions, DispatchOptions } from 'vuex'
interface CustomCommit<Mutations> {
(type: Mutations, payload?: any, options?: CommitOptions): void
}
interface CustomDispatch<Actions> extends Dispatch {
(type: Actions, payload?: any, options?: DispatchOptions): Promise<any>
}
// {ActionContext} from 'vuex
export interface CustomActionContext<State, RootState, Actions, Mutation> {
dispatch: CustomDispatch<Actions>
commit: CustomCommit<Mutation>
state: State
getters: any
rootState: RootState
rootGetters: any
}
export type CustomActionTree<
State,
RootState,
Actions extends string,
Mutations
> = {
[key in Actions]: (
context: CustomActionContext<State, RootState, Actions, Mutations>,
payload?: any
) => any
}
export type CustomMutationTree<State, Mutations extends string> = {
[key in Mutations]: Mutation<State>
}
import { CounterActions, CounterMutations } from '~/store/counter.enum'
import { CustomActionTree, CustomMutationTree } from '~/store/vuex-custom'
export type RootState = null
export type CounterModuleState = {
count: number
}
export type CounterModuleMutations = CustomMutationTree<
CounterModuleState,
CounterMutations
>
export type CounterModuleActions = CustomActionTree<
CounterModuleState,
RootState,
CounterActions,
CounterMutations
>
export enum CounterMutations {
UpCount = 'upCount',
DownCount = 'downCount'
}
export enum CounterActions {
UpCount = 'upCount',
DownCount = 'downCount'
}
import {
CounterModuleActions,
CounterModuleMutations,
CounterModuleState
} from '~/store/counter'
import { CounterMutations } from '~/store/counter.enum'
export const state = (): CounterModuleState => ({
count: 0
})
export const mutations: CounterModuleMutations = {
upCount(state) {
state.count++
},
downCount(state) {
state.count--
}
}
export const actions: CounterModuleActions = {
upCount(context) {
context.commit(CounterMutations.UpCount)
},
downCount(context) {
context.commit(CounterMutations.DownCount)
}
}