Using Vue.js to process JSON data

My issue lies within this JSON data.

I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js.

This line of code in the console works: 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>

Answer №1

If your template is trying to display data before it's ready from an AJAX request, consider using a flag to track when the data is available and toggle the display using the v-if directive.

Here's an example:

Template

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

Script

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

In your created hook, update the flag:

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

Alternatively, you can initialize your noticias array with some placeholder data like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send the byte array stored in a Session object to an Asp.Net 2.0 asmx Web Service using a JSON object

I have a code snippet that involves working with byte arrays in a web service: The Session["timestamp"] contains a byte array retrieved using Linq to Entity. However, when I call the function, it throws an error. The web service function is as follows: ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

Using the window.history.pushState function triggers a page reload every time it is activated

I've been attempting to navigate from page to page without the need for a reload. I came across suggestions that using window.history.pushState() could achieve this, however, it appears that the page is still reloading. Furthermore, an attempt ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

Parts are tuned in to information within the main component

Visit this link I am trying to control the text color of "box" elements with a checkbox. <div id="app"> <label><input type='checkbox' v-model='showBlack' />Show black</label> <box>Hello</box& ...

Why do developers opt for getServerSideProps() over a standard asynchronous function in their code?

Recently, I decided to experiment with the getServerSideProps() function. While I understand it must have its purpose, to me it seems similar in utility to a typical async function. Take for example my current task of retrieving user data using Prisma and ...

Having trouble retrieving PHP variable values using JavaScript?

<div id="div01">01</div> <div id="div02">02</div> <img src="../img/logo.png" onclick="blueSky()"/> js function blueSky() { $.ajax({ type:'GET', url: 'test.php', success: function(respond) { document.ge ...

Unexpected additional character found in json_encode output

I'm attempting to generate a correctly formatted JSON output using CodeIgniter, but it seems like there is an unnecessary hyphen or dash character in the result displayed below: Below is the snippet of code I'm using to produce the query result: ...

Using the nlohmann JSON library to construct nested JSON objects in C++

I'm currently utilizing the https://github.com/nlohmann/json library and it's been working smoothly for me. However, I've encountered some challenges in generating the desired JSON output below: { "Id": 1, "Child": [ { ...

Issue with AngularJS: Copying and appending with $compile is not functioning properly

Below is the snippet of my angularjs Controller var $tr = angular.element("#parent" + obj.field_id).find("tbody"), $nlast = $tr.find("tr:last"), $clone = angular.copy($nlast); $clone.find(':text').val('' ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

Using v-icon in a Vuetify text-area label instead of plain textHttpFoundation showcase of v-icon integration within V

Looking to use v-icon in the label of a Vuetify text-area instead of just plain text? Wondering how it can be done effectively? <v-textarea outlined label="DEMO" value="Hello World" /> This is what I attempted: <v-textarea outlined la ...

having trouble iterating through nested arrays in JSON within Excel VBA with the JsonConverter.bas library obtained from Github

A snippet from a JSON file is shown below: { "data": [ { "id": "6003510075864", "name": "Golf", "audience_size": 242637550, "path": [ "Interests", "Sports and outdoors", ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

What is the best way to transfer form data into a Django template using JSON dump?

I need assistance with importing a POST request from a form template.html to my view.py using the following code: data=json.dumps(request.POST) The data in view.py is formatted like this: {"5": "25", "4": "28", "6": "21"} When trying to run any dictio ...

Having trouble passing a variable in an AQL Json file through Jfrog CLI

We are embarking on a mission to identify expired artifacts in our Artifactory enterprise version using AQL query and JFrog CLI. To achieve this, I aim to introduce a variable in the AQL JSON file to facilitate the deletion of these artifacts through JFro ...

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

Tips on transferring information from a component to an instance in Vue

My goal is to retrieve data from a component and transfer it to a variable within my root Vue instance. Vue Instance Configuration: new Vue({ el: '#root', data: { searchResultObject: '' }, methods: { // ...