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 as simple as Vue rendering the items when they are ready. For example, check out this Vue SFC Playground

<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

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

The Discord.js command outright declines to function

I'm having trouble with a code that I'm working on. The goal is to create a command that is enabled by default, but once a user uses it, it should be disabled for that user. However, when I try to execute the code, it doesn't work at all and ...

What is the best way to locate the position of a different element within ReactJS?

Within my parent element, I have two child elements. The second child has the capability to be dragged into the first child. Upon successful drag and drop into the first child, a callback function will be triggered. What is the best way for me to determi ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

Error: jQuery Validation not triggering in Bootstrap modal window

My attempts to use jQuery Validation for form validation inside a modal have hit a dead end. The validation doesn't trigger at all, not even an error message is displayed. Upon debugging, a warning emerged: No elements selected for validation; retu ...

Troubleshooting issues with adding child elements in JavaScript

Styling with CSS: ul #allposts li{ height: 50px; width: 50px; background-color: yellow; border: 1px solid yellow; } Creating HTML structure: <ul id = "allposts"></ul> Adding JavaScript functionality: var container = documen ...

Vite and Transloadit encountered a type error: Unable to access properties of undefined when trying to read 'Resolver'

Currently, I am developing a Vite application using Vue 3.x that involves interactions with images/PDFs through Transloadit. While working on creating my own plugin for Transloadit integration, I encountered some issues. Initially, I managed to resolve an ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...

Navigating through JSON arrays with Node.js

I have been given the task of iterating through a complex JSON file that contains an array of JSON objects. I am finding it difficult to access the array object within the JSON file. Specifically, I need to access the "class-name" object from the JSON f ...

What is this error: "Unknown authentication strategy 'loca'"?

Whenever I try to utilize passport.js, it keeps throwing the following error: Unknown authentication strategy "local"! config/configuration.js var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Executing Python and JavaScript with Selenium

I am encountering an issue while trying to run this code. The error message indicates that I may be missing a closing ) or using an illegal character. It seems like there might be confusion with inserting arguments where they are not needed. Could someon ...

Unraveling the Mysteries of Ajax Debugging

I am currently facing a perplexing issue with a program I created. Until recently, everything was functioning perfectly fine. However, at present, I am encountering initialization problems that have left me puzzled. From my understanding, it seems that the ...

AngularJS: Implementing a toggle click function for a list of items within an iframe

Here's the workflow I'm dealing with: I have a collection of items, each having an ng-click event that triggers the display of an iframe below the clicked item. The process works like this: When clicking an item, a hidden div tag beneath it ap ...

Select checkboxes by clicking a button that matches the beginning of a string in JavaScript

I have a form with a list of users and checkboxes below their names. Each user has a button that should select all checkboxes assigned to them. Below is the code for the dynamically created buttons and checkboxes. The included function takes the form name ...

Example of material-ui-pickers: Error - Object(...) is not a function

Trying to implement a basic material UI pickers example using a clean project and following the installation and usage instructions provided here: An error message is displayed as follows: TypeError: Object(...) is not a function Module../node_modules/@m ...