What is the best way to display an object in Vue.js once it has been retrieved through an AJAX request?

Imagine having the following HTML code:

<div id="app">
        <h2>List of Items</h2>
        <table border="1">
            <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Category</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in items">
                <td>${item.name}$</td>
                <td>${item.price}$</td>
                <td>${item.category}$</td>
            </tr>
            </tbody>
        </table>
</div>

Let's create a Vue script like this:

        var app = new Vue({
            delimiters: ['${', '}$'],
            el: '#app',
            data: {
                //I want to replace this hard-coded list with array fetched from API
                items: [
                    { name: "Keyboard", price: 44, category: 'Accessories'},
                    { name: "Mouse", price: 20, category: 'Accessories'},
                    { name: "Monitor", price: 399, category: 'Accessories'},
                    { name: "Dell XPS", price: 599, category: 'Laptop'},
                    { name: "MacBook Pro", price: 899, category: 'Laptop'},
                    { name: "Pencil Box", price: 6, category: 'Stationary'},
                    { name: "Pen", price: 2, category: 'Stationary'},
                    { name: "USB Cable", price: 7, category: 'Accessories'},
                    { name: "Eraser", price: 2, category: 'Stationary'},
                    { name: "Highlighter", price: 5, category: 'Stationary'}
                ]
            },
        });

How can one make an AJAX request to fetch the items data and update the Vue component once the response is received?

Using something similar to this might seem intuitive, but it doesn't quite work:

        let items;
        function fetchData() {

            var ajaxSendRequest = $.ajax({
                url: '{{ path('get_items') }}',
                type: 'GET',
                dataType: 'json'
            });
            ajaxSendRequest.done(function (data) {
                //assign the fetched data to the items variable
                items = data;
            }).fail(function (textStatus, errorThrown) {

            });
        }
    
//you can then use it in the Vue component

If you're unfamiliar with this process, or if the above method doesn't work as expected, what would be the correct approach to achieving the same result? (fetching data from an API and rendering it)

Answer №1

Start by creating a method in Vue to handle your ajax code.

In the Vue app, methods are defined as follows:

methods: {
    getHello() {
        ...
    }
},

The methods property is placed within the Vue instance, similar to data.

Once the method is created, you can set your products by using this.products, where this refers to the Vue instance of that component.

For example:

methods: {
    getHello() {
        ...
        this.products = ajaxResponse;
    }
},

Subsequently, you can utilize the products data variable within your Vue component, and it will be "reactive," meaning Vue automatically updates it when it changes.

However, there's an issue when your method uses a callback. Inside the callback function, this won't point to the Vue instance. To work around this, do the following:

methods: {
    getHello() {
        const $vm = this;
        ...
            // Inside your callback
            $vm.products = ajaxResponse;
    }
},

This approach allows us to create a locally scoped version of this that references back to the Vue instance so we can access it within our callback where the original Vue this would have been overridden.

You can then call this method inside the mounted() lifecycle hook:

mounted() {
    this.getHello();
}

Answer №2

Retrieving data and displaying a list is made easy with Vue, where items are rendered when ready. Check out this example at:

<template>
        <h2>List of Products</h2>
        <table border="1">
            <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Category</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(product, index) in localProducts" :key="index">
                <td>{{product.name}}</td>
                <td>{{product.price}}</td>
                <td>{{product.category}}</td>
            </tr>
            </tbody>
        </table>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
  mounted(){
      setTimeout(() => {
        this.localProducts = this.serverProducts
      }, 3000)
  },
  data() {
    return {
      localProducts: undefined,
      serverProducts: [
        { name: "Keyboard", price: 44, category: 'Accessories'},
        { name: "Mouse", price: 20, category: 'Accessories'},
        { name: "Monitor", price: 399, category: 'Accessories'},
        { name: "Dell XPS", price: 599, category: 'Laptop'},
        { name: "MacBook Pro", price: 899, category: 'Laptop'},
        { name: "Pencil Box", price: 6, category: 'Stationary'},
        { name: "Pen", price: 2, category: 'Stationary'},
        { name: "USB Cable", price: 7, category: 'Accessories'},
        { name: "Eraser", price: 2, category: 'Stationary'},
        { name: "Highlighter", price: 5, category: 'Stationary'}
      ]
    }
  }
});
</script>

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

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Material Design Autocomplete search feature in Angular 2

I'm encountering some challenges with autocomplete in Angular2 Material Design. Here are the issues I'm facing: 1. When I type a character that matches what I'm searching for, it doesn't display in the autocomplete dropdown as shown in ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...

Steps for accessing the files uploaded in a React application

Looking to implement an upload button using material UI that allows users to upload multiple files, with the goal of saving their paths into an array for future use. However, I'm unsure about where these uploaded files are stored. The code snippet be ...

Confirm the data within an HTML table and apply color coding to the cells appropriately

Currently, I have an HTML table used to automatically validate data collected from soil pollutants analyses. Here is a snippet describing the table structure: <table id="table1"> <thead class="fixedHeader"> <tr><input type="submit" ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Exploration of features through leaflet interaction

Attempting to plot bus routes on a map using leaflet with geojson for coordinates. Facing issues with making the bus line bold when clicked, and reverting the style of previously clicked features back to default. Current Progress function $onEachFeature( ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

What is the process for changing the selected value after it has been clicked and removing the previous selection

Is there a way to change the class of a li element in a PHP view after it has been clicked? <ul> <li> <a href="<?=base_url()?>home" id="home" onclick="select_class('home');" class="shortcut-dashboard" title="Home">Home& ...

I need help figuring out how to send a POST/GET request from AJAX to a custom module controller in Odoo 10, but I'm running into issues

I have implemented a custom module in Odoo 10 with a simple controller. Everything works smoothly when accessing http://127.0.0.1:8069/cmodule/cmodule through the browser, displaying the expected return string. However, I encountered an issue when attempt ...

React Redux is facing difficulties resolving its own modules

Upon running webpack for my project, an error regarding the React-Redux package not being able to resolve some of its internal modules has been encountered: ERROR in ./node_modules/react-redux/es/index.js Module not found: Error: Can't resolve ' ...

Leveraging the power of jQuery's $.when and $.then methods for efficiently managing multiple AJAX requests that do not

My goal is to utilize jQuery to retrieve data from both an XML and JSON feed, and then only log the data when both requests are successful. When I comment out getRoomFeed() within the $.when, it returns the correct responseText object for the XML. However ...

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

Utilizing the GData API for seamless integration with cross-domain ajax requests

I need to retrieve XML data from Google's server using its API. I am unable to modify the response, so how can I make this call work for me: $.ajax({ type: 'POST', url: 'https://www.google.com/accounts/ClientLogin', ...

The getElementByID function functions properly in Firefox but does encounter issues in Internet Explorer and Chrome

function switchVideo() { let selectedIndex = document.myvid1.vid_select.selectedIndex; let videoSelect = document.myvid1.vid_select.options[selectedIndex].value; document.getElementById("video").src = videoSelect; } <form name="myvid1"> <s ...

Failure to update hit counter in MySQL database using Ajax request

Below is the code snippet for loading a list of videos from a database on the index page: <?php ini_set('display_errors', 1); mysqli_set_charset($link, 'utf8mb4'); $query="SELECT * FROM videos"; $result=mysqli_query($lin ...

Utilizing dynamic JSON lists in Spring MVC

Currently, I have a new form for Person that includes a table of objects structured like so: <table class="table table-striped table-condensed flip-content"> <thead class="flip-content"> <tr> <th width="20%"> ...

Dynamic css property implementation in Vue list rendering

I am currently working on creating a carousel-style list of items similar to the iOS native date/time pickers, where the list can be shifted both upwards and downwards. The positioning of each item is determined by the `top` property from a model, which i ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...