Rumah > Soal Jawab > teks badan
Dalam projek saya, saya mempunyai fungsi untuk memuat turun fail. Apabila butang diklik, fungsi onDownload
akan dipanggil:
import {useOnDownload} from "../../use/useOnDownload" setup() { ... const loading = ref(null) onDownload = (id) => { loading.value = id await useOnDownload(id) loading.value = null } return {loading, onDownload} }
Saya memfaktorkan semula kod api dalam fail panggilan useOnDownload.js
kerana komponen lain juga menggunakan kod yang sama.
export async function useOnDownload(id) { // make api call to server with axios }
Apa salah saya? Saya perlu menunggu fungsi useOnDownload ... untuk pemuat berfungsi dengan baik.
P粉0715596092024-03-26 15:31:51
Berikut ialah cara mencipta fungsi boleh gubah tak segerak menggunakan sintaks tunggu async
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();
Klik di siniuntuk maklumat lanjut
P粉7640035192024-03-26 09:19:39
Saya berjaya menyelesaikan cara lain tanpa async dan menunggu...
Saya menyerahkan pemuat objek rujukan kepada hujah fungsi (sebagai pilihan) dan mengendalikannya dari sana...
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 } }) }