【问题标题】:Fetch each object from API data using vue and axios使用 vue 和 axios 从 API 数据中获取每个对象
【发布时间】:2020-07-07 21:38:15
【问题描述】:

这是我的脚本,它调用 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 获取的 SAMPLE 数据如下所示

POSTS OBJECT VARIABLES

我能够在控制台日志中获取 API DATA 作为一个数组,但是当我从 createdAT 数组中调用一个对象时,v-text = "post.createdAt" 不会打印/获取 createdAt 日期列表的列表。

【问题讨论】:

标签: vue.js axios render


【解决方案1】:

刚刚解决了这个问题,使用 AXIOS TO CONSUME API 这里是那个 https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html 的链接。

我发布的以上代码工作正常。问题出在我的 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)
  }

【讨论】:

    【解决方案2】:

    posts 不是响应式的,因为默认值为 null,请将其设为空数组,或者改用 Vue.set

    数组:

    posts: []
    

    Vue.set:

    .then(response => Vue.set(this, 'posts', response.data))
    

    编辑

    针对以下cmets:

    您必须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>
    

    【讨论】:

    • 当我使用你的建议时,我现在得到的错误是迭代中的错误元素期望有 'v-bind:key' 指令 vue/require-v-for-key 和错误 'Vue ' 未定义
    • @sandeshphuyal 我编辑了我的答案以说明您为什么会遇到这些问题。这些是 Vue 本身的一些基本概念,希望对您有所帮助。
    猜你喜欢
    • 2021-03-07
    • 2021-09-22
    • 2021-05-26
    • 2021-09-22
    • 2020-09-27
    • 2018-09-03
    • 2018-01-31
    • 2022-12-05
    • 2019-08-03
    相关资源
    最近更新 更多