在我的專案中,我有一個(gè)下載檔案的功能。當(dāng)點(diǎn)擊按鈕時(shí),函數(shù) 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
呼叫檔案中重構(gòu)了 api 程式碼,因?yàn)槠渌彩褂昧讼嗤某淌酱a。
export async function useOnDownload(id) { // make api call to server with axios }
我做錯(cuò)了什麼?我需要等待函數(shù) useOnDownload ... 才能讓載入程式正常運(yùn)作。
以下是如何使用 async wait 語法建立非同步可組合函數(shù)
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();
點(diǎn)擊此處以了解更多資訊
我設(shè)法解決了另一種沒有異步和等待的方法...
我將引用物件載入器傳遞給函數(shù)參數(shù)(作為可選)並從那裡處理...
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 } }) }