vue3 自定义 hooks 优雅处理异步调用 ajax
2021-05-30 03:01
标签:const ref imp err cti sea efi final on() 首先自定义一个专门处理异步的 hooks 用法为: 另外,如果想自动触发调用,可以进异步封装如下: 则用法为: vue3 自定义 hooks 优雅处理异步调用 ajax 标签:const ref imp err cti sea efi final on() 原文地址:https://www.cnblogs.com/muamaker/p/14693341.htmlimport {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}};
})
上一篇:CSS基础知识及其基本语法
下一篇:jQuery的css样式操作
文章标题:vue3 自定义 hooks 优雅处理异步调用 ajax
文章链接:http://soscw.com/index.php/essay/89371.html