2017-08-18 159 views
1

我的问题是使用这个json。 http://dev-rexolution.pantheonsite.io/api/noticiasVue.js使用json

我需要消耗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> 
+0

你究竟是什么意思的*“不工作”*?另外,为什么要为您的网址使用字符串模板文字? – Phil

+0

快速浏览您的浏览器*控制台*和*网络*开发工具应该会显示您可能遇到的任何问题 – Phil

+0

此模板由Drupal 8模块Rest生成。不工作,因为它将对象返回为undefined –

回答

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 }] 
}] 
+0

谢谢!现在工作 –

+0

这是因为它好? –

+0

对不起@Fabián,我不明白你的问题 – Phil