在我的项目中,我有一个下载文件的功能。当点击按钮时,函数 onDownload 将被调用:
import {useOnDownload} from "../../use/useOnDownload"
setup() {
...
const loading = ref(null)
onDownload = (id) => {
loading.value = id
await useOnDownload(id)
loading.value = null
}
return {loading, onDownload}
}
我在 useOnDownload.js 调用文件中重构了 api 代码,因为其他组件也使用了相同的代码。
export async function useOnDownload(id) {
// make api call to server with axios
}
我做错了什么?我需要等待函数 useOnDownload ... 才能使加载程序正常工作。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
以下是如何使用 async wait 语法创建异步可组合函数
export default function useOnDownload() { const isLoading = ref(true); const onDownload = async () => { isLoading.value = true; try { const { data } = await axios.post('/api/download', {id: id}, {responseType: 'blob'}) // handle the response } catch (error) { console.log(error); } finally { isLoading.value = false; } }; // invoke the function onDownload(); return { // return your reactive data here }; } import useOnDownload from "../../use/useOnDownload" // no await in setup script or function const { reactiveDataReturned } = useOnDownload();点击此处了解更多信息
我设法解决了另一种没有异步和等待的方法...
我将引用对象加载器传递给函数参数(作为可选)并从那里处理...
export function useOnDownload(id, loader) { if(loader !== undefined) { loader.value = id } axios.post('/api/download', {id: id}, { responseType: 'blob' }).then(response => { // handle the response ... if(loader !== undefined) { loader.value = null } }).catch(error => { // handle the error ... if(loader !== undefined) { loader.value = null } }) }