在 vue 應用程式上,在組件上,呼叫 API 以獲取一些資料...問題是在呼叫結束之前獲取undefined ......可能需要 aync/await 但在添加時出錯
//component code (login.vue)
import store from "@/store";
const { response, error } = store.postTO(url, [{id: "button1"}, {id: "button2"}, {id: "button3"}]);
if (response) {
console.log(response);
} else {
console.warn(error);
}
//store.js
export default {
user : null,
postTO
}
function postTO(url, postData) {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: JSON.stringify(postData)
};
return fetch(url, requestOptions).then(response =>
response.json().then(data => ({
data: data,
status: response.status
})
).then(res => {
console.log(res.data);
return {response : res.data, error : "test"};
}))
.catch(error => {
return {response : "test", error : error};
});
}
插圖

uj5u.com熱心網友回復:
在組件中,您必須通過在 store.posTo 之前放置一個 await 來等待獲取
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332923.html
標籤:javascript Vue.js
