Vuex TypeScript - ChoDragon9/posts GitHub Wiki

Vuex๋Š” ์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ API๋กœ ์ •์˜์ธก๊ณผ ์‚ฌ์šฉ์ธก์ด ๋ฃจ์ฆˆํ•˜๊ฒŒ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋‹ค. ์ด๋ฒคํŠธ ๊ธฐ๋ฐ˜ API์—์„œ ๋น„๋กฏ๋˜๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ช‡๊ฐ€์ง€ ์žˆ๋‹ค.

1. ์•ก์…˜๊ณผ ๋ฎคํ…Œ์ด์…˜ ์‚ฌ์šฉ ์‹œ, ์‚ฌ์šฉ์ธก์—์„œ ์ •์ƒ์ ์œผ๋กœ ์ •์˜๋˜์—ˆ๋Š” ์ง€ ๋Ÿฐํƒ€์ž„์„ ํ†ตํ•ด์„œ๋งŒ ์•Œ ์ˆ˜ ์žˆ๋‹ค.
2. ์ƒ์ˆ˜๋ฅผ ํ†ตํ•ด ์ •์˜์ธก๊ณผ ์‚ฌ์šฉ์ธก์„ ์ผ์น˜์‹œ์ผœ๋„ ํ•ด๋‹น ๋ชจ๋“ˆ๊ณผ ์ผ์น˜ํ•˜์ง€ ์•Š๋Š” ์•ก์…˜ ์‚ฌ์šฉ์‹œ, ๋Ÿฐํƒ€์ž„์„ ํ†ตํ•ด์„œ๋งŒ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

๊ฒฐ๊ตญ ๋Ÿฐํƒ€์ž„์„ ํ†ตํ•ด์„œ๋งŒ ์ •์ƒ๋™์ž‘์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ๊ธฐ์„œ๋Š” ์ปดํŒŒ์ผํƒ€์ž„์—์„œ ์ •์ƒ์ ์œผ๋กœ ๋™์ž‘ํ•จ์„ ์•Œ ์ˆ˜ ์žˆ๊ฒŒ ํƒ€์ž…์„ ์ถ”๊ฐ€ํ–ˆ๋‹ค.

Types

vuex custom

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
>

Store

enum

export enum CounterMutations {
  UpCount = 'upCount',
  DownCount = 'downCount'
}
export enum CounterActions {
  UpCount = 'upCount',
  DownCount = 'downCount'
}

counter

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)
  }
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ