标签:const ref imp err cti sea efi final on()
首先自定义一个专门处理异步的 hooks
import {reactive, toRefs} from "vue"; const useAsyncFn = (fn)=>{ let data = reactive({value:undefined ,loading:false,err:undefined}); const callBack = (...args)=>{ data.loading = true; fn(...args).then((res)=>{ data.value = res; },(err)=>{ data.err = err }).finally(()=>{ 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}}; })
标签:const ref imp err cti sea efi final on()
原文地址:https://www.cnblogs.com/muamaker/p/14693341.html