2017-08-18 173 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