Fabián
Fabián

Reputation: 39

Vue.js consume json

My problem is with this json. http://dev-rexolution.pantheonsite.io/api/noticias

I need to consume with vuejs 2 only the first element of the array to be able to display it, working with the console I worked but with no vuejs.

This console log work: 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>

Upvotes: 1

Views: 968

Answers (1)

Phil
Phil

Reputation: 164733

You're probably running into an issue where your template is attempting to show data that doesn't exist until the AJAX request has completed.

I would set a flag to indicate when the data is available and toggle the display using v-if. For example

Template

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

Script

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

and in your created hook

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

Alternatively, set up your initial noticias array with some dummy data

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

Upvotes: 1

Related Questions