【发布时间】:2021-10-23 13:23:06
【问题描述】:
在 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};
});
}
【问题讨论】:
-
因为is是一个异步进程,所以需要等待结果。如果你使用的是 vuex。然后从任何方法调用
postTO,并在 API 结果将其变异为 vuex 状态变量后,将变量读回 vue -
你还需要等待 store.postTo
标签: javascript vue.js