VueUse useAsyncState ,它会将异步结果包裹在一个响应式对象中,在执行异步操作时,将对象中的loading属性设置为true,执行完后loading属性设置为false,并将结果更新state或error属性。
import { computed, onMounted, reactive } from 'vue';
import axios from 'axios'
import { useAsyncState } from '@vueuse/core'
const result = useAsyncState(
(args) => {
return axios.get(`https://debug.itxst.com/static/vueuse-demo/user.json`).then(t => t.data)
},
{},
{
delay: 3000,
resetOnExecute: false,
},
)
例子
<template>
<div>
<p>Ready: {{ result.isReady }}</p>
<p>Loading: {{ result.isLoading }}</p>
<pre >{{ result}}</pre>
<button @click="result.execute(2000, { id: 2 })">
点击执行ajax请求
</button>
</div>
</template>
<script setup lang="ts">
/*
vueuse 中文文档
https://www.itxst.com/vueuse/tutorial.html
*/
import { computed, onMounted, reactive } from 'vue';
import axios from 'axios'
import { useAsyncState } from '@vueuse/core'
const result = useAsyncState(
(args) => {
return axios.get(`https://debug.itxst.com/static/vueuse-demo/user.json`).then(t => t.data)
},
{},
{
delay: 3000,
resetOnExecute: false,
},
)
</script>