Pulling Data in Vue.js using AJAX

Currently trying out Vue.js and I must say, it's impressively simpler than Angular. My single page app is utilizing vue-router and vue-resource to connect to my API backend. The primary app.js loads vue-router and vue-resource along with separate components for each route.

I am faced with a dilemma: How can I utilize props to pass global data fetched through asynchronous AJAX calls to child components? For instance, having the list of users accessible by any child component after fetching the data in the primary app.js. My goal is to make only one API call for the entire application. Are there alternative solutions I should consider?

Currently, when using props in the child components, I only receive an empty array initially assigned to the users variable before the asynchronous AJAX call fetches the actual data. Here's a snippet of the code:

Sample App.js

// Vue setup
// Router map defined

var App = Vue.extend({
    ready: function() {
        this.fetchUsers();
    },

    data: function() {
        return {
            users: [],
        };
    },

    methods: {
        fetchUsers: function() {
            // Asynchronous AJAX request to fetch users data
        }
    }
});

// Router initialization
router.start(App, '#app')

Sample app.html

<div id="app" v-cloak>
    <router-view users="{{ users }}">
    </router-view>
</div>

Sample dashboard.js

module.exports = {
    component: {
        ready: function() {
            console.log(this.users);
        },

        props: ['users'],
    },
};

Upon running dashboard.js, an empty array is logged to the console due to the initial value set in app.js. How do I grant access to the updated users variable from app.js within dashboard.js? Your assistance is much appreciated!

p.s. Excluding the usage of inherit: true as I only want specific app.js variables available in child components.

Answer №1

It seems that the issue lies in the asynchronous nature of the $http call, leading to a misconception that it is not functioning correctly. The reason behind this confusion is that the console.log statement is being executed before the completion of the $http call.

To address this problem, consider setting up a watcher on the component for changes in the users data and include a console.log statement within that watcher function.

Here's an example implementation:

module.exports = {
    component: {
        ready: function() {
            console.log(this.users);
        },

        props: ['users'],

        watch: {
            users: {
                handler: function (newValue, oldValue) {
                    console.log("Current value of users:", this.users);
                },
                deep: true
            }
        }
    }
};

Answer №2

The latest iteration of Vue 1.0.0+ introduces a streamlined way to ensure that users within your component are always up-to-date:

<div id="app" v-cloak>
    <router-view :users="users"></router-view>
</div>

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

When multiple instances of a Vue Filepond component are used on the same page, the input event emitter is saving the data in the v-model of the last

A new file-uploader component has been developed with the following setup: <template> <div> <file-pond :id="id" :key="id" name="files" ref="pond" v-bind="$attrs" v-on:activatefile="onActivateFileCli ...

Adding numeric values to a user-friendly URL following the selection of a number

My website is primarily focused on showcasing photo galleries for visitors to browse. Users can navigate to the gallery of images from the main page, and within the gallery, they have the option to select specific photos to view. The image below illustrat ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

Is it possible to harness the power of Vue.js without relying on the npm and node modules

Greetings! Currently working on a new project where I am restricted from utilizing webpack, node modules, and CDNs for specific reasons. This Vue project will exclusively consist of client-side components without any backend considerations or routing req ...

The VLC WebPlugin puts a halt on websocket activity during playback

I currently have a basic HTML/JS application that includes an embedded VLC WebPlugin and several methods for play/pause functionality. This application is being managed by another JavaScript file through a straightforward server/websocket C# setup. The con ...

Tips for utilizing AJAX to send data from a specific row

<table> <tr data-id="1"> <input type="text" name="name_1" value="abc"> <input type="text" name="value_1" value="1"> <a href="load_edit_row(this)">Edit</a> </tr> <tr data-id="2"> <input t ...

Struggling to make JavaScript read JSON data from an HTML file

I am currently working on developing a word search game using django. One of the tasks I need to accomplish is checking whether the entered word exists in a dictionary. To achieve this, I have been converting a python dictionary into JSON format with json. ...

What is the reason behind the change in encoding?

I'm working on a project hosted on a local webserver, with all files saved in UTF-8 format. The sqlite database also uses UTF-8 encoding and handles German letters like ä, ö, ü perfectly. However, when I upload the project to the hosting server, th ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Is "content_scripts" malfunctioning in Chrome version 38 and above?

Just recently, I created a Chrome Extension with the purpose of making all webpages utilize a specific font. Everything was functioning perfectly fine until yesterday (or possibly even earlier). The crucial codes for this extension are: manifest.json fil ...

Heroku, paired with Redis, consistently records information and monitors for socket errors

I have recently implemented Heroku, Redis, and Node.js with Express in my project. I successfully set up caching using Redis in my Node app, but I noticed continuous logs appearing in the Heroku log console in this format: 2024-04-21T18:54:09.000000+00:00 ...

Unexpected error while using Uploadify

I'm having trouble trying to make Uploadify (2.1.4) work. When I check in Google Chrome Inspector, there are no errors during initialization. However, when I click on the select files button, nothing happens and pressing the upload button gives me thi ...

The issue of Nuxt i18n routing not functioning properly with sub pages

After modifying my app to integrate with nuxt i18n, I encountered an issue where the translations only work when accessing routes directly. For example, http://localhost:3000/fr/step/1 My app has a structured layout where each step is represented by a di ...

The response function is not defined in the Facebook error message

if (response.status === 'connected') { $.ajax({ url: 'https://graph.facebook.com/oauth/access_token', type: 'GET', data:'grant_type=fb_exchange_token&client_id="done"&c ...

What is the reason for the unique behavior of v-bind with boolean attributes? More specifically, why is the number 0 considered truthy in

According to the official documentation, <button v-bind:disabled="isButtonDisabled">Button</button> In this example, the disabled attribute will be added if isButtonDisabled is equal to 0, despite the fact that in JavaScript, 0 is co ...

Switch the checkbox back if an error occurs

I'm having an issue with a styled checkbox that appears to flip when clicked. Upon user interaction, the checkbox visually flips on the client side, while sending a request to save the change in a database on the server. In case of an error, I need to ...

Steps for incorporating a side panel next to a component with carbon components

I'm working on a Sveltekit app and I want to create a homepage that displays a table using carbon components. The twist is, I also need to add a filter panel next to the table for data filtering. Essentially, I am aiming to achieve something similar t ...

Suggestions for autocomplete in a textarea within an HTML element

<!DOCTYPE html> <html> <head> <base href="http://demos.telerik.com/kendo-ui/autocomplete/index"> <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style> <title></title> ...

Executing a Shortcode Using a Button in Visual Composer for Wordpress

It should be easy to do this. I've got a great plugin with a modal newsletter signup form that offers various launch options, including manual launching with the following codes. https://i.stack.imgur.com/IGbsp.png My theme utilizes Visual Composer. ...

Google Maps: Customize infoWindow Layout

I'm having trouble figuring out how to change the default frame of an infoWindow in Google Maps. Here's my code where I create a marker and add a listener that opens an info window: var markerPosition = new google.maps.LatLng(lat, lng); ...