Upgrade to Pro — share decks privately, control downloads, hide ads and more …

VuexからPinia移行に向けて

ツノ
March 21, 2023
260

 VuexからPinia移行に向けて

ツノ

March 21, 2023
Tweet

Transcript

  1. Pinia の前に:Vue の現状 多くのチームが Vue3 移行に悩むはず CLI ツール(VueCLI → Vite)

    UI フレームワーク(Vuetify) 状態管理ライブラリ(Vuex → Pinia) その他の破壊的変更... 今回は状態管理ライブラリについて Vuex:Vue 公式のライブラリ(Vuex4 まで) Pinia:Vuex5 として開発
  2. Pinia を使ってみて:Store 定義 Vue の Options や Composition っぽい書き方ができる Store、Getter、Action

    を定義できる 例:Composition での書き方 export const useCounterStore = defineStore("counter", () => { const count = ref<number>(0); // Store const doubleCount = computed(() => count.value * 2); // Getter function increment() { count.value++; // Action } return { count, doubleCount, increment }; });
  3. Pinia を使ってみて:Store 呼び出し Store を import して呼び出すだけで利用できる Store をリアクティブに使いたい場合は storeToRefs(store)

    を利用 <script setup lang="ts"> import { useCounterStore } from "./HelloWorld.store"; const store = useCounterStore(); </script> <template> <h1 v-text="store.name" /> <button type="button" @click="store.increment()"> count is {{ store.count }} </button> </template>
  4. Pinia を使ってみて:テスト @pinia/testing の createTestingPinia をマウント時に定義 Action のみ Mock したりできる。Vuex

    より柔軟にテストが書けそう。 const wrapper = mount(HelloWorld, { global: { plugins: [ createTestingPinia({ initialState: { counter: { count: 100 } } }), ], }, }); const store = useCounterStore(); // Store呼び出し const incrementSpy = vi.spyOn(store, "increment"); // モック化 incrementSpy.mockImplementation(() => (store.count += 2)); wrapper.find("button").trigger("click"); expect(wrapper.text()).toContain("count is 102");
  5. Vuex から Pinia への移行 手順 公式 Options にマイグレーションを推奨 → Options

    への移行はステップごとに説明 Mutation 廃止によるモジュール再構築発生 懸念点 グローバルな状態を移行する影響範囲怖い テスト作る工数に時間とられそう
  6. EOF