useAsyncState
反应式异步状态。不会阻止你的设置函数,并且一旦 promise 准备就绪就会触发更改。默认状态为 shallowRef
。
¥Reactive async state. Will not block your setup function and will trigger changes once the promise is ready. The state is a shallowRef
by default.
示例
Ready: false
Loading: true
{}
用法
¥Usage
ts
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 },
)
手动触发异步函数
¥Manually trigger the async function
你也可以手动触发它。当你想要控制异步函数的执行时间时,此功能非常有用。
¥You can also trigger it manually. This is useful when you want to control when the async function is executed.
vue
<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">
Execute now
</button>
<button class="ml-2 button" @click="event => execute(500, event.target)">
Execute with delay
</button>
</template>