使用 vue 和 axios 从 API 数据中获取每个对象
Fetch each object from API data using vue and axios
这是我调用 axios 并将数据作为帖子获取的脚本
<script>
import axios from 'axios'
export default {
name: 'App',
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data)
},
data() {
return {
posts: null
}
},
};
</script>
我的视图代码试图从上面的脚本中获取数据作为帖子
<template>
<div id="app">
<ul>
<li v-for="post in posts" v-text="post.createdAt"></li>
</ul>
<div>
</template>
从 API URL 获取的样本数据如下所示
POSTS OBJECT VARIABLES
我能够在控制台日志中获取 API DATA 作为数组,但是当我从数组中调用一个对象时,它是 createdAT,v-text = "post.createdAt"
没有 print/fetch createdAt 日期列表列表。
posts
不是反应式的,因为默认值为 null
,将其设为空数组,或改用 Vue.set
:
数组:
posts: []
Vue.set:
.then(response => Vue.set(this, 'posts', response.data))
编辑
回应以下评论:
您必须 import Vue from 'vue'
解决 Vue
未定义错误。
关于您的 v-for-key
需要是唯一的,您需要在 v-for 元素上定义一个唯一的 key
。您可以只使用 JSON.stringify(post)
:
<li v-for="post in posts" v-text="post.createdAt" :key="JSON.stringify(post)"></li>
刚刚按照本文档使用 AXIOS 消费 API 解决了它,这里是 https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html 的 link。
我发布的以上代码运行良好。问题出在我的 API URL 上,它嵌套在 data[data[object]] 中。所以我从 API
调用数据的方式
来自这个
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data)
}
到这个
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data.data)
}
这是我调用 axios 并将数据作为帖子获取的脚本
<script>
import axios from 'axios'
export default {
name: 'App',
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data)
},
data() {
return {
posts: null
}
},
};
</script>
我的视图代码试图从上面的脚本中获取数据作为帖子
<template>
<div id="app">
<ul>
<li v-for="post in posts" v-text="post.createdAt"></li>
</ul>
<div>
</template>
从 API URL 获取的样本数据如下所示
POSTS OBJECT VARIABLES
我能够在控制台日志中获取 API DATA 作为数组,但是当我从数组中调用一个对象时,它是 createdAT,v-text = "post.createdAt"
没有 print/fetch createdAt 日期列表列表。
posts
不是反应式的,因为默认值为 null
,将其设为空数组,或改用 Vue.set
:
数组:
posts: []
Vue.set:
.then(response => Vue.set(this, 'posts', response.data))
编辑
回应以下评论:
您必须 import Vue from 'vue'
解决 Vue
未定义错误。
关于您的 v-for-key
需要是唯一的,您需要在 v-for 元素上定义一个唯一的 key
。您可以只使用 JSON.stringify(post)
:
<li v-for="post in posts" v-text="post.createdAt" :key="JSON.stringify(post)"></li>
刚刚按照本文档使用 AXIOS 消费 API 解决了它,这里是 https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html 的 link。
我发布的以上代码运行良好。问题出在我的 API URL 上,它嵌套在 data[data[object]] 中。所以我从 API
调用数据的方式来自这个
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data)
}
到这个
mounted: function () {
axios.get('API URL')
.then(response => this.posts = response.data.data)
}