vue.js - 将 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]
“数据数组”是我需要的详细信息,谁能告诉我如何获取这些数据。
解决方案
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;
});
}
}
}
推荐阅读
- mongodb - 如何在MongoDB中将两个顺序查询变成单个查询
- json - 从另一个文件中填充变量,在 bash/shell 脚本中读取用户输入
- c# - C# Unity Script 有没有办法加快实例化
- gae-python27 - Python27-try/except 问题
- mysql - 从 MySQL Workbench 中的数据导入向导导入 CSV 文件
- database - 在 Hadoop 或分布式计算框架中管理多个集群
- javascript - 我可以在离线时连接到 localhost WebSocket,即没有互联网连接吗?
- python - Pyqt:在没有鼠标焦点的情况下更新小部件
- objective-c - 什么是 AVPlayerItem 超时值?
- javascript - 如何拦截 XMLHttpRequest 并更改请求 URL