首先自定义一个专门处理异步的 hooks
import {reactive, toRefs, ref } from "vue"; const useAsyncFn = (fn)=>{ let data = reactive({value:undefined ,loading:false,err:undefined}); let lastCallId = ref(0); const callBack = (...args)=>{ data.loading = true; const callId = ++lastCallId.value; // 避免短时间内,多次触发。导致结果错乱 fn(...args).then((res)=>{ if(callId === lastCallId.value){ data.value = res; data.loading = false; } },(err)=>{ if(callId === lastCallId.value){ data.err = err data.loading = false; } }) } return [toRefs(data),callBack]; } export default useAsyncFn
用法为:
let [data,callback] = useAsync(async(a)=>{ let project = await fetch("/xxx?a="+a).then(res=>res.json()); let iteration = await fetch("/xxx").then(res=>res.json()); return {project,iteration}}; }) onMounted(()=>{ callback(1) })
另外,如果想自动触发调用,可以进异步封装如下:
import useAsyncFn from "./useAsyncFn" const useAsync = (fn)=>{ const [ data,callback ] = useAsyncFn(fn); callback(); return data; } export default useAsync;
则用法为:
let res = useAsync(async()=>{ let project = await fetch("/xxx").then(res=>res.json()); let iteration = await fetch("/xxx").then(res=>res.json()); return {project,iteration}}; })