【问题标题】:Vue.js consume jsonVue.js 消耗 json
【发布时间】:2018-01-26 13:15:57
【问题描述】:

我的问题在于这个 json。 http://dev-rexolution.pantheonsite.io/api/noticias

我只需要使用 vuejs 2 使用数组的第一个元素才能显示它,使用我工作的控制台但没有 vuejs。

这个控制台日志工作:console.log(response.data[0].title[0].value);

<template>
  <div class="Box Box--destacado1">
    <div class="Media Media--rev">
      <div class="Media-image">
          </div>
              <div class="Media-body">
                <span class="Box-info">{{ noticias[0].field_fecha[0].value}}</span>
                <h3 class="Box-title">
                 <a href="">{{ /*noticias[0].title[0].value */}}</a>
                </h3>
               <p class="Box-text">{{/*noticias[0].field_resumen[0].value*/}}</p>
              </div>
            </div>
</template>

<script>
import axios from 'axios';

export default {
  data: () => ({
    noticias: [],
    errors: []
  }),

  // Fetches posts when the component is created.
  created() {
    axios.get(`http://dev-rexolution.pantheonsite.io/api/noticias`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.noticias = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

【问题讨论】:

  • “不工作”到底是什么意思?另外,为什么要为您的 URL 使用字符串模板文字?
  • 快速浏览浏览器的 ConsoleNetwork 开发工具应该会发现您可能遇到的任何问题
  • 此模板由 Drupal 8 模块 Rest 生成。不起作用,因为它将对象返回为未定义
  • 你必须比这更清楚; “将对象返回为未定义” 在哪里?哪段代码导致错误?如果您的网络应用程序在 http://localhost:8080 上运行,这应该适合您
  • 这段代码在访问 json 元素时不起作用。 {{ noticias[0].field_fecha[0].value}}

标签: javascript json vue.js vuejs2


【解决方案1】:

您可能遇到了一个问题,即您的模板试图显示在 AJAX 请求完成之前不存在的数据。

我会设置一个标志来指示数据何时可用,并使用v-if 切换显示。例如

模板

<div class="Media-body" v-if="loaded">

脚本

data () {
  loaded: false,
  noticias: [],
  errors: []
}

在你的 created 钩子里

.then(response => {
  this.loaded = true
  this.noticias = response.data
})

或者,使用一些虚拟数据设置您的初始 noticias 数组

noticias: [{
  title: [{ value: null }]
  field_fecha: [{ value: null }]
  field_resumen: [{ value: null }]
}]

【讨论】:

  • 对不起@Fabián,我不明白你的问题
  • @Fabián 问题是,您的模板正试图以非常特定的结构访问数据。当noticias 只是一个空数组时,您会遇到错误。如果你让它至少在结构上像你的模板所期望的那样,它就不会出错
  • 哇,谢谢@Phil
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多