• vue3 自定义 hooks 优雅处理异步调用 ajax


    首先自定义一个专门处理异步的 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}};
        })
    

      

  • 相关阅读:
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    将Ojective-C代码移植转换为Swift代码
    Swift
    房费制——报表(1)
  • 原文地址:https://www.cnblogs.com/muamaker/p/14693341.html
Copyright © 2020-2023  润新知