【Nuxt Typescript】vuex-module-decoratorsを使ってみた
はじめに
vuex-module-decoratorsは、class構文でvuexを書くデコレーター。
これまでのNuxt Typescriptはcommitやdispatchを使用することで
型の推論が途切れてしまうという問題があった。
それを解決するツールとして最近スタンダードに使われているのがこのvuex-module-decoratorsらしいので試してみた。
全体像
axiosの設定部分は // axios としています。
~/store/index.tsと~/utils/store-accessor.tsが storeとコンポーネントをタイプセーフに繋ぐ役割を持っています。 ( これを別々のファイルとして定義している理由があんまりよくわかっていない... )
component └ comp.vue store ├ index.ts └ sampleStore.ts utils ├ api.ts // axios └ store-accessor.ts plugins └ axios-accessor.ts // axios
ノーマルなvuexと比較
ノーマルなvuex
import { MutationTree, ActionTree, GetterTree } from 'vuex' import { CounterState, RootState } from '@/store/types'; export const state = (): CounterState => ({ count: 0 }) export const getters: GetterTree<CounterState, RootState> = { getCount: state => state.count } export const mutations: MutationTree<CounterState> = { increment(state: CounterState, delta: number): void { state.count += delta } } export const actions: ActionTree<CounterState, RootState> = { incr({ commit }) { commit('increment', 5) } }
vuex-module-decorators
vuex-module-decorators
import { Module, VuexModule, Mutation, Action } from 'vuex-module-decorators' interface CounterState { count: number } @Module export default class Counter extends VuexModule { // state count: number = 0 // getters getCount() { return this.count } @Mutation increment(delta: number) { this.count += delta } // action 'incr' commits mutation 'increment' when done with return value as payload @Action({ commit: 'increment' }) incr() { return 5 } }
感想
個人的にはvuex-module-decoratorsの方が見た目もスッキリしているし 型もパッとみてわかりやすい気がするのでありかなと思います。