首页 > 解决方案 > 将 API 中的数据渲染到 Vue 模板中

问题描述

我在 vue 中成功获取 api 但如何正确渲染它?“undefined id of null”是我在控制台错误中得到的

这是我打的 axios 电话

  axios.getOrder(id).then(response => {
    this.cart_content = response.data
    console.log(this.cart_content)
  })

这就是我试图在 vue 中渲染的方式

       <div v-if="cart_content">
          <ul v-for="i in cart_content" :key="i.id">
            <li>
              <p>{{i.name}}</p>
              <p>{{i.items.quantity}}</p>
              <p>{{i.items.unit_price}}</p>
            </li>
          </ul>
        </div>

当我 console.log 时 API 可用,它看起来像这样。

id:'',
data:array[1]

“数据数组”是我需要的详细信息,谁能告诉我如何获取这些数据。

标签: vue.js

解决方案


Because your data is collected in an asynchronous way, it's not initially available to your component, hence it errors out. You'll need to fetch the data on a component lifecycle method, something like this:

import axios from 'axios';

export default {
  data() {
    return {
      cart_content: [],
      id: ''
    }
  },
  created() {
    this.getOrder(this.id)
  },
  methods: {
    getOrder(id) {
      axios.getOrder(id)
        .then(response => {
          this.cart_content = response.data;
        });
    }
  }
}

Working CodeSandbox Example


推荐阅读