了解です!
では続けて 第4章 4.3 コード比較(Before / After)(フルサンプル付き) に進みます。
ここでは、今まで進めてきた
useStore
)useCounterStore
)この3つの状態を並べて比較しながら振り返ることで、変換の全体像を整理します。
<template>
<ChildComponent :count="count" @increment="incrementCount" />
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { mapState, mapMutations } from 'vuex';
import ChildComponent from './ChildComponent.vue';
@Component({
components: { ChildComponent },
computed: { ...mapState(['count']) },
methods: { ...mapMutations(['increment']) },
})
export default class ParentComponent extends Vue {
incrementCount() {
this.increment();
}
increment!: () => void;
get count(): number {
return 0; // mapStateで上書き
}
}
</script>
<template>
<button @click="increment">Increment</button>
<p>Count from parent: {{ count }}</p>
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { Prop, Emit } from 'vue-property-decorator';
@Component
export default class ChildComponent extends Vue {
@Prop({ type: Number, required: true })
count!: number;
@Emit('increment')
increment() {}
}
</script>
useStore
使用)<template>
<ChildComponent :count="count" @increment="incrementCount" />
</template>
<script lang="ts" setup>
import { useStore } from 'vuex';
import { State } from '@/store';
import { computed } from 'vue';
import ChildComponent from './ChildComponent.vue';
const store = useStore<State>();
const count = computed(() => store.state.count);
function incrementCount() {
store.commit('increment');
}
</script>