๐ŸŽฏ 7.3 ้žๅŒๆœŸๅ‡ฆ็† + Composition API ใฎใƒ†ใ‚นใƒˆไพ‹

๏ผˆPromiseใƒปasync/await ใ‚’ๅซใ‚€ Composition API ใ‚ณใƒณใƒใƒผใƒใƒณใƒˆใฎใƒ†ใ‚นใƒˆ๏ผ‰


โœ… ใ€่ฆ็‚นใ€‘

โ†’ Vuex ใฎ action ใ‚„ๅ†…้ƒจใฎ async ้–ขๆ•ฐใ‚’ใƒ†ใ‚นใƒˆใ™ใ‚‹ใจใใฏๅฟ…้ ˆ็Ÿฅ่ญ˜ใ€‚


๐ŸŸข ใ€้žๅŒๆœŸ dispatch ใ‚’ๅ‘ผใถ Composition API ใ‚ณใƒณใƒใƒผใƒใƒณใƒˆใ€‘

<!-- AsyncCounter.vue -->
<template>
  <button @click="incrementAsync">+</button>
</template>

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

const store = useStore();

const incrementAsync = async () => {
  await store.dispatch('incrementAsync'); // โ† ้žๅŒๆœŸ action
};
</script>


๐ŸŸ  ใ€Vuex ใฎ้žๅŒๆœŸ action ใฎไพ‹ใ€‘

// store/counter/actions.ts
export const actions = {
  async incrementAsync({ commit }: any) {
    await new Promise((resolve) => setTimeout(resolve, 500)); // 500ms ๅพ…ใค
    commit('increment');
  },
};


๐ŸŸฃ ใ€ใƒ†ใ‚นใƒˆๆ™‚ใฎใƒใ‚คใƒณใƒˆใ€‘

  1. dispatch ใ‚’ใƒขใƒƒใ‚ฏใ—ใฆ Promise ใ‚’่ฟ”ใ™
  2. await ใ‚’ใคใ‘ใฆใƒ†ใ‚นใƒˆใ‚’ๆญฃใ—ใๅพ…ใค
  3. ๅฟ…่ฆใชใ‚‰ nextTick ใ‚‚ไฝฟใ†