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

Creating a mandatory 'Select' dropdown field in Vue.js

Hello, I am a beginner in VueJS and I am trying to make a select element from a drop-down list required. I attempted to add the required attribute as shown in the code below. Any suggestions on how to achieve this? Thanks. <v-select ...

The battle between HTML5's async attribute and JS's async property

What sets apart the Html5 async attribute from the JS async property? <script src="http://www.google-analytics.com/ga.js" async> versus (function() { var ga = document.createElement('script'); ga.type = 'text/javascript&apo ...

Utilizing Ajax to serialize or transfer JSON objects

I have received a Json object and I am looking to extract the data using JavaScript. Specifically, I need help with looping through fields and extracting the data. def For_Sale_Listing(request,id): try: listing = Listing.objects.filter(pk=id) ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Display an aspx page within a div container

I am using the following code to load an aspx page in a div tag. Unfortunately, it's not working as expected. Can someone please assist me in resolving this issue? <script type="text/javascript"> $(document).ready(function () { $(&a ...

Steps for converting a Calendar into a JSON format

I am working on developing a REST application like the one shown below: @XmlRootElement @Entity @Table(name = "tb_verarq") public class Verificacao implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue ...

Number input in JavaScript being disrupted by stray commas

On my webpage, there are elements that users can control. One of these is a text input field for numbers. When users enter digits like 9000, everything functions correctly. However, if they use comma notation such as 9,000, JavaScript doesn't recogniz ...

Using ng-repeat with valid json does not function properly

When receiving a response from Java servlet via Angular, the request content is in 'text/html' format and I utilized 'data.split' to process it: d = response.data.replace(/^\s+|\s+$/g, ''); // remove /r/n data = d.s ...

Searching for matching strings in jQuery and eliminating the parent div element

Here's an HTML snippet: <div id="keywords"> <div id="container0"> <span id="term010"> this</span> <span id="term111"> is</span> <span id="term212"> a</span> <span ...

Leveraging @click within dropdown selections - Vue.js 2

Is there a way to implement the @click event in select options? Currently, I have the following: <button @click="sortBy('name')">sort by name</button> <button @click="sortBy('price')">sort by price</button> Th ...

The jQuery functions are unable to function properly when retrieving AJAX data

I am currently working on a script that inserts a record into my database using AJAX. After inserting the data, it is posted back in the following format... Print "<li>"; Print "<span class='cost'>" . $bill. "</span> "; Print ...

Using Javascript to dynamically populate dropdown options based on radio button selection

I am in the process of developing a basic form that allows users to input the frequency of a specific report. Initially, users were only able to enter days of the week. However, due to changes in demand for certain reports, options such as workday and day ...

Linking two div elements together with a circular connector at the termination point of the line

I am currently working on designing a set of cards that will showcase a timeline. I envision these cards to be connected by lines with circles at each end, for a visually appealing effect. At the moment, I have created the cards themselves but I am struggl ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Tips on obtaining a Firebase ID

Does anyone have a solution for retrieving the unique id from Firebase? I've attempted using name(), name, key, and key() without any success. Although I can view the data, I'm struggling to find a way to retrieve the id. This information is cru ...

Shifting an element to the right before revealing or concealing it with Jquery Show/Hide

$(document).ready(function(){ var speed = 700; var pause = 3500; function removeFirstElement(){ $('ul#newsfeed li:first').hide('slide', {direction: "up"}, speed, function() {addLastElement(thi ...

Issue with setting a cookie on a separate domain using Express and React

My backend is hosted on a server, such as backend.vercel.app, and my frontend is on another server, like frontend.vercel.app. When a user makes a request to the /login route, I set the cookie using the following code: const setCookie = (req, res, token) = ...

A JavaScript function that instantiates an object that invokes its own function

Currently, I am working on an Angular service that is meant to return a new object. Everything seems to be fine and in working order. When I use new MakeRoll(), it successfully creates an instance. However, the issue arises when I call self.add towards th ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

What is the method for obtaining a dynamic route path within the pages directory in Next.js?

In my code, I have a special Layout component that compares routing queries and displays the appropriate layout based on the query. I'm looking to extend this functionality to handle dynamic routing scenarios, such as invoices/invoice-1. Currently, ...