【问题标题】:waiting fetch to get the data等待 fetch 获取数据
【发布时间】: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


【解决方案1】:

在组件中,您必须通过在 store.posTo 之前放置 await 来等待获取

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2020-06-17
    • 2022-07-06
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多