Steps for Displaying Data from API Response in Vue.js

Immediately rendering the following template, without waiting for the API call to complete.

I came up with a solution using v-if to prevent elements from rendering until the data is available.

However, this seems to go against the DRY principle as I have to wrap my elements with v-if statements.
Is there a different approach to tackle this issue? Another way to code it?

<template>
    <div id="app">
        <div v-if="obj">
            <h2>{{ obj[0].item }}</h2>
        </div>
        <div v-if="obj">
            <h5>{{ obj[0].id }}</h5>
        </div>
    </div>
</template>
<script>
export default {
    name: 'app',
    data() {
        return {
            obj: []
        }
    },
    mounted: function() {
        axios.get(URL)
            .then(response =>
                this.obj = response
            });
}
}
</script>

Answer №1

A solution is available if you are utilizing Vue Router - https://router.vuejs.org/en/advanced/data-fetching.html

The data will be fetched immediately after the route is activated by monitoring the $route object

You can also refer to a similar answer I provided here: Check permissions before vue.js route loads

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

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

What is the method to store anchor text in a Session variable?

I'm currently working on a project where I've linked multiple pdf files in the master page. When clicking the anchor, the page redirects to the specified location and displays the pdf in an iframe. Now, I want the text within the anchor tag to be ...

Issue loading a 300 MB file into BigQuery results in a timeout error

Trying to implement the Node.js example shown in the data post request section (located towards the end here: https://cloud.google.com/bigquery/loading-data-post-request) has hit a snag when dealing with larger files. While the sample code functions proper ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Scaling Vuetify icons dimensions

During the development of an app using Vuetify, I encountered challenges in changing the default colors set by Vuetify. After some trial and error, I came across a solution on: https://github.com/vuetifyjs/vuetify/issues/299 The solution involved adding ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

NodeJS - issues with nodemon auto-reload feature causing my server to not

After successfully installing NodeJS version 4.4.5, I proceeded to install nodemon version 1.9.2 by following all the installation instructions using npm (npm install -g nodemon). In a newly created folder, I have my server.js file with some basic code: ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

Utilizing WordPress to dynamically update the footer content on a targeted webpage by modifying the HTML/PHP/JS code

Let me provide some clarity. Details: - Website built on WordPress This website is bilingual with Hebrew and English languages. The issue is with the footer section. I have 4 lines that need to display: - Address: ........ - Phone: ....... - Fax: ...... - ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...