在我的專案中,我有一個下載檔案的功能。當點擊按鈕時,函數 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 ... 才能讓載入程式正常運作。
P粉0715596092024-03-26 15:31:51
以下是如何使用 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();
點擊此處以了解更多資訊
P粉7640035192024-03-26 09:19:39
我設法解決了另一種沒有異步和等待的方法...
我將引用物件載入器傳遞給函數參數(作為可選)並從那裡處理...
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 } }) }