【发布时间】:2021-05-10 14:25:46
【问题描述】:
我正在尝试从 axios get 请求中获取数据,然后尝试从另一个 axios get 请求的响应中更新它。但是,我无法呈现来自第二个请求的数据。
示例代码摘录为:
// api.js
// fetch items - first api call
fetchItems() {
const ITEMS_ENDPOINT = `${ROOT_URL}/items`;
return axios.get(ITEMS_ENDPOINT, config);
},
// fetch items info - 2nd api call
fetchItemsInfo(itemId) {
const ITEMS_INFO_ENDPOINT = `${ROOT_URL}/items/${itemId}`;
return axios.get(ITEMS_INFO_ENDPOINT, config);
},
// vue component
methods: {
async fetchItems() {
const res = await api.fetchItems();
this.items = res.data;
console.log(this.items);
// console output [{id:1, a:1}, {id:2, a:2}, {id:3, a:3}]
},
updateItems() {
this.items.forEach(async (item) => {
const itemId = item.id;
const res = await api.fetchItemsInfo(itemId);
const info = res.data;
console.log(info);
// console output {id:1, x:2}
if (item.id === info.id) {
item.x = info.x;
console.log(item);
// console output [{id:1, a:1, x:2}]
}
});
},
},
async created() {
await this.fetchItems();
this.updateItems();
console.log(this.items);
// console output [{id:1, a:1, x:0}, {id:2, a:2, x:1}, {id:3, a:3, x:2}]
},
// html
<ul>
<li v-for="(item, index) in items" :key="index">
<!-- out put is (only the data from 1st call is displayed):
1 || 1 ||
2 || 2 ||
3 || 3 ||
-->
{{ item.id }} || {{ item.a }} || {{ item.x }}
</li>
</ul>
只显示来自第一次 api 调用的数据,而不是来自第二次调用的数据。
我可以记录来自created 钩子的数据,它会在控制台中按预期显示。
如果我使用单击(按钮单击)方法调用updateItems 函数,则数据按预期呈现。但是,我希望在页面加载时加载它。
即使我从 updateItems 更新 vuex 状态并渲染状态获取器,我也会得到相同的行为。
如何也渲染第二次调用的数据?
非常感谢
【问题讨论】:
-
问题主要出在你使用的 forEach 块上,你可以试试这个stackoverflow.com/questions/37576685/…
-
@ThakurKarthik
for..of也不走运。 -
我试着在这里做一个小repro jsbin.com/yuzuvoyefe/edit?html,js,console,output如果有用可以检查一次吗?
-
它仍然不适合我。
标签: javascript api vue.js vuejs2 axios