javascript - 如何使用 axios 在 Vue 应用程序中获取、更新和渲染数据?

标签 javascript api vue.js vuejs2 axios

我正在尝试从 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 Hook 记录数据,它会按预期显示在控制台中。 如果我使用单击(按钮单击)方法来调用 updateItems 函数,则数据将按预期呈现。但是,我希望在页面加载时加载它。

即使我从 updateItems 更新 vuex 状态并渲染状态 getter,我也会得到相同的行为。

如何渲染第二次调用的数据?

非常感谢

最佳答案

问题在于您正在向响应式(Reactive)项目添加新属性。这是行不通的。我认为这应该对你有用,因为你正在重新创建整个对象而不是添加新属性

updateItems() {
  this.items = this.items.map(async item => {
    const { data: info } = await api.fetchItemsInfo(item.id);
    return {
      ...item,
      ...info
    }
  });
},

如果您知道属性名称,您也可以使用 Vue.set(如果需要)

Vue.set(item, 'property1', info.property1)
Vue.set(item, 'property2', info.property2)
etc...

我认为这会满足您的要求,但我也认为仅将详细信息添加到获取项目调用的响应中比为每个项目发出额外请求要便宜得多。

关于javascript - 如何使用 axios 在 Vue 应用程序中获取、更新和渲染数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66076929/

相关文章:

javascript - 部署云函数时出现 Nuxt.js 错误

javascript - jQuery UI slider - 防止多个 handle 重叠

php - Youtube Zend Api函数中断脚本

android - Ruby on Rails REST API 与可离线工作的 Android 客户端

mysql - 如何在数据库查询中区分 403 和 404

mysql - 如何在Vue中从数据库渲染html

javascript - Chrome 不显示 Javascript 警告框

javascript - jQuery - Ajax POST 似乎不起作用

javascript - 显示来自其他地方的对象的数据

javascript - Vue.js:重新定义图表数据