(Vue 2.7 クラスコンポーネント → Composition API 書き換え実例)
クラスコンポーネントでは this.$store.dispatch()
/ this.$store.commit()
を使っていた。
Composition API では
→ useStore()
で store を取得し、store.dispatch()
/ store.commit()
を使う。
→ 型安全も強化でき、Vue 3 以降もそのまま使える形になる。
<!-- Counter.vue -->
<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>
<!-- Counter.vue -->
<template>
<button @click="increment">+</button>
</template>
<script lang="ts" setup>
import { useStore } from 'vuex';
const store = useStore();
const increment = () => {
store.dispatch('increment');
};
</script>
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('dispatch が呼ばれる', async () => {
const actions = { increment: jest.fn() };
const store = new Vuex.Store({ actions });
const wrapper = shallowMount(Counter, { store, localVue });
await wrapper.find('button').trigger('click');
expect(actions.increment).toHaveBeenCalled();
});
});
import { shallowMount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';
// dispatch のモック
const dispatchMock = jest.fn();
jest.mock('vuex', () => ({
useStore: () => ({
dispatch: dispatchMock,
}),
}));
describe('Counter.vue (Composition API)', () => {
beforeEach(() => {
dispatchMock.mockClear();
});
it('ボタンをクリックすると dispatch increment が呼ばれる', async () => {
const wrapper = shallowMount(Counter);
await wrapper.find('button').trigger('click');
expect(dispatchMock).toHaveBeenCalledWith('increment');
});
});