useAsyncState
useAsyncState
リアクティブな非同期状態。setup 関数をブロックせず、Promise が準備できたら変更をトリガーします。状態はデフォルトで shallowRef です。
使用法
import { useAsyncState } from '@vueuse/core'
import axios from 'axios'
const { state, isReady, isLoading } = useAsyncState(
axios
.get('https://jsonplaceholder.typicode.com/todos/1')
.then(t => t.data),
{ id: null },
)
非同期関数を手動でトリガーする
手動でトリガーすることもできます。これは、非同期関数を実行するタイミングを制御したい場合に便利です。
<script setup lang="ts">
import { useAsyncState } from '@vueuse/core'
const { state, execute, executeImmediate } = useAsyncState(action, '', { immediate: false })
async function action(event) {
await new Promise(resolve => setTimeout(resolve, 500))
return `${event.target.textContent} clicked!`
}
</script>
<template>
<p>State: {{ state }}</p>
<button class="button" @click="executeImmediate">
今すぐ実行
</button>
<button class="ml-2 button" @click="event => execute(500, event)">
遅延実行
</button>
</template>
© 2019–PRESENT Anthony Fu https://github.com/antfu
※このページは Nuxt.js 公式ドキュメントの翻訳ページです。
公式ドキュメントの該当ページはこちら:
#