2017-10-19 34 views
0

有一種表單將一些數據提交給組件中的API。假設它的方法是ProcessLogin()。在這個函數裏面,我使用axios編寫了我的API調用。在then()的幫助下,我處理了我的服務器響應並顯示了我的麪包。都好。一個接一個地執行自定義函數 - Vue.js中的回調邏輯

現在作爲我的代碼清理的一部分,我決定將我所有的axios函數移動到另一個api.js文件並從那裏導出函數。下面是一個例子功能我在api.js文件:

function ApiLogin(data) { 
const url = `${BASE_URL}/authenticate`; 
axios.post(url,data).then(response => { 
    return response; 
}).catch(error => { 
    return error.response; 
}); 
} 

在我的組件另一邊,我已經定義了我的方法如下:

methods: { 
    ProcessLogin() { 
    var status = ApiLogin(this.data); 
    console.log(status); 
} 
} 

當執行這一點,我得到未定義我安慰。我知道它爲什麼會發生。因爲consoleLog(狀態)在ApiLogin可以處理併發送響應之前執行。如何處理這種情況。?我知道回調是在這裏拯救,但我不確定如何整合它。

回答

1

如果您從ApiLogin返回Axios公司通話功能:

function ApiLogin(data) { 
    const url = `${BASE_URL}/authenticate` 
    return axios.post(url, data) 
} 

然後,您可以使用然後處理在組件的響應從那裏和控制檯日誌:

methods: { 
    ProcessLogin() { 
    ApiLogin(this.data) 
     .then(res => console.log(res)) 
     .catch(err => console.log(err)) 
    } 
} 

...或用異步/等待

methods: { 
    ProcessLogin: async function() { 
    try { 
     var status = await ApiLogin(this.data) 
     console.log(status) 
    } 
    catch(err) { 
     console.log(err) 
    } 
    } 
} 
+0

完美。謝謝。 –

+0

沒問題。很高興這幫助你。 –

相關問題