🎯 4.1 this.$store.dispatchuseStore().dispatch への書き換え

(Vuex を使う Composition API 化とテストの書き換え)


✅ 【要点】

クラスコンポーネントでは Vuex の操作を

this.$store.dispatch('アクション名')

Composition API に書き換えると

const store = useStore();
store.dispatch('アクション名');

👉 Vuex ストアへのアクセス方法が完全に変わる。

👉 Jest のテストでは useStore() をモックする必要がある。


🟢 【Before: クラスコンポーネントでの Vuex】

🎯 コンポーネント(クラス)

<template>
  <button @click="increment">+</button>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component
export default class Counter extends Vue {
  increment(): void {
    this.$store.dispatch('increment');
  }
}
</script>

🧪 テスト(Before)

import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Counter from '@/components/Counter.vue';

const localVue = createLocalVue();
localVue.use(Vuex);

describe('Counter.vue', () => {
  it('increment action を dispatch する', () => {
    const actions = { increment: jest.fn() };
    const store = new Vuex.Store({ actions });

    const wrapper = shallowMount(Counter, {
      store,
      localVue,
    });

    wrapper.find('button').trigger('click');
    expect(actions.increment).toHaveBeenCalled();
  });
});


🟠 【After: Composition API + useStore】

🎯 コンポーネント(Composition API)

<template>
  <button @click="increment">+</button>
</template>

<script lang="ts" setup>
import { useStore } from 'vuex';

const store = useStore();
const increment = () => {
  store.dispatch('increment');
};
</script>