Heim  >  Fragen und Antworten  >  Hauptteil

Async Wait funktioniert nicht in Composable Function Vue 3

In meinem Projekt habe ich eine Funktion zum Herunterladen von Dateien. Wenn auf die Schaltfläche geklickt wird, wird die Funktion onDownload aufgerufen:

import {useOnDownload} from "../../use/useOnDownload"

setup() {

    ...

    const loading = ref(null)
    onDownload = (id) => {
        loading.value = id
        await useOnDownload(id)
        loading.value = null
    }
    
    return {loading, onDownload}
}

Ich habe den API-Code in der useOnDownload.js-Aufrufdatei umgestaltet, da auch andere Komponenten denselben Code verwenden.

export async function useOnDownload(id) {
    // make api call to server with axios
}

Was habe ich falsch gemacht? Ich muss auf die Funktion useOnDownload ... warten, damit der Loader ordnungsgemäß funktioniert.

P粉752826008P粉752826008207 Tage vor472

Antworte allen(2)Ich werde antworten

  • P粉071559609

    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();

    点击此处了解更多信息

    Antwort
    0
  • P粉764003519

    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
         }
       })
    }

    Antwort
    0
  • StornierenAntwort