Having trouble displaying API JSON data in a Vue.js table component

In my HTML file, I have implemented fetching data from an API and displaying it in a table successfully.

Now, I am trying to convert the HTML file to use Vue.js, but encountering some issues. Despite being able to fetch data from the API with Vue, the table is not showing on the webpage. (I have exported JSONTable.vue and imported it into App.vue for access)

The external sources used in my HTML files that draw the table successfully are:

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 

To address template errors in Vue, I replaced them within the script tag as follows:

import JQuery from 'jquery'
let $ = JQuery

How can I incorporate the external stylesheet and script mentioned above in Vue without the need for 'import JQuery' (to avoid '$ is not defined' error)?

Here is a snippet of my Vue site:

<template>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <!-- styling the table with an external css file -->
    <body>
        <div class="container">
            <div class="table-responsive">
                <h1>JSON data to HTML table</h1>
                <br />
                <table class="table table-bordered table-striped" id="tracerouteTable">
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>salary</th>
                        <th>age</th>
                        <th>image</th>
                    </tr>
                </table>
            </div>
        </div>
    </body>
</head>
</template>

<script>

export default {
    name: 'JSONTable'
}


import JQuery from 'jquery'
let $ = JQuery 



$(document).ready(function(){
    $.getJSON("http://dummy.restapiexample.com/api/v1/employees", function(data){
        var employeeData = '';

        console.log(data);

        $.each(data, function(key, value){
            employeeData += '<tr>';
            employeeData += '<td>'+value.id+'</td>';
            employeeData += '<td>'+value.employee_name+'</td>';
            employeeData += '<td>'+value.employee_salary+'</td>';
            employeeData += '<td>'+value.employee_age+'</td>';
            employeeData += '<td>'+value.profile_image+'</td>';
            employeeData += '<tr>';
        });
        $('#tracerouteTable').append(employeeData);
    });
});

</script>

Answer №1

Instead of relying on jQuery when working with Vue, it is often unnecessary in the majority of cases.

I have put together an example to demonstrate how you can achieve your goals without using jQuery. Here are two key points to keep in mind:

NOTE 1: The CORS restrictions prevent data from loading in this example. I have used mocked data instead.

NOTE 2: To ensure compatibility across different browsers, utilize a polyfill like github fetch alongside the fetch API for making HTTP requests.

const initialData = () => {
  return Promise.resolve([
    {"id":"40877","employee_name":"Lexie","employee_salary":"3331","employee_age":"60","profile_image":""},{"id":"40878","employee_name":"Randi","employee_salary":"9608","employee_age":"29","profile_image":""},{"id":"40879","employee_name":"Wilber","employee_salary":"9626","employee_age":"58","profile_image":""},{"id":"40881","employee_name":"Jena","employee_salary":"3669","employee_age":"47","profile_image":""},{"id":"40882","employee_name":"Annetta","employee_salary":"8428","employee_age":"45","profile_image":""},{"id":"40883","employee_name":"Blaze","employee_salary":"9090","employee_age":"60","profile_image":""},{"id":"40884","employee_name":"Vida","employee_salary":"8633","employee_age":"54","profile_image":""},{"id":"40885","employee_name":"Tyrese","employee_salary":"1133","employee_age":"55","profile_image":""},{"id":"40888","employee_name":"Assunta","employee_salary":"8291","employee_age":"37","profile_image":""},{"id":"40889","employee_name":"Talon","employee_salary":"7896","employee_age":"35","profile_image":""},{"id":"40891","employee_name":"Selina","employee_salary":"6091","employee_age":"68","profile_image":""},{"id":"40892","employee_name":"Madyson","employee_salary":"2057","employee_age":"39","profile_image":""}])
}

new Vue({
  el: '#app',
  data: function (){
    return {
      list: []
    }
  },
  mounted: async function (){
    /*
     NOTE 1: This example does not work due to CORS restrictions preventing data loading
     so I am using mocked data
     
     NOTE 2: Using fetch for HTTP requests, consider using Github fetch or other similar polyfills
     */
    
    
     //const response = await fetch("//dummy.restapiexample.com/api/v1/employees")
     //this.list = await response.json()
    this.list = await initialData()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 
<div id="app">
  <div class="table-responsive">
    <h1>JSON data to HTML table</h1>
    <br />
    <table class="table table-bordered table-striped" id="tracerouteTable">
      <thead>
        <tr>
          <th>id</th>
          <th>name</th>
          <th>salary</th>
          <th>age</th>
          <th>image</th>
        </tr>
       </thead>
      <tbody>
        <tr v-for="item in list" :key="item.list">
          <td>{{item.id}}</td>
          <td>{{item.employee_name}}</td>
          <td>{{item.employee_salary}}</td>
          <td>{{item.employee_age}}</td>
          <td>{{item.profile_image}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</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

Sticky Sidebar Attached to Parent Container with Smooth Sliding Effect

Is it possible to have my sidebar push the content across when opened, while keeping the fixed navigation relative to its parent element instead of the viewport? The sidebar works fine in Firefox but breaks out of the parent in Chrome. Link to JSFiddle & ...

JavaScript code using jQuery's ajax method is sending a request to a PHP server, but

Attempting to utilize jQuery ajax for PHP call and JSON return. The test is quite simple, but only receiving an empty object in response. No PHP errors appearing in the LOG File. jqXHR is recognized as an object with 'alert', yet not displayin ...

Overlap of columns within a nested flexbox arrangement

While working with React and Styled Components, I encountered a problem of elements overlapping each other: https://i.stack.imgur.com/RuCYu.png There are a few instances of overlap, including: The padding below the <ul> element is colliding with ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...

Utilizing shared data properties in both JavaScript and SCSS within Vue

Vue.js 2 has caught my interest, especially with the single-file component structure: <template> <h1>Hello World</h1> </template> <script> export default { name: 'hello-world', }; </script> <style s ...

refresh-free form clearing

Currently, I am working on a form that includes Recaptcha validation using jQuery. The form is functioning well as the information is sent to my email and all required fields are checked before submission. However, there is one issue that I am encounterin ...

Is there a way to ensure uniform font display across all browsers?

Is there a way to ensure consistent font display across all browsers? I am facing an issue with font consistency on my webpage. While browsers like Internet Explorer Edge and 11, Chrome, and Firefox display the desired font correctly, Internet Explorer 8 ...

Switching the delimiter for JSON queries using Json.net

Currently, I am utilizing the Newtonsoft Json library to query a JSON string by employing the SelectToken method, which utilizes "." as a delimiter to navigate through the JSON hierarchy in accordance with the documentation provided here: https://www.newt ...

Sending a file to the jqGrid handler

Currently, I am using Grails in combination with jqGrid and attempting to implement a rather unique feature. My goal is to allow users to upload a file which will then be sent to the jqGrid controller and used as a filter for the data displayed on the grid ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

The upload directory in KCFinder can be accessed and selected using a URL

Issue: While using the link to open kcfinder as defined in kcfinder, I encountered a problem. The link is intended to open kcfinder with the provided parameters: window.open('/kcfinder/browse.php?type=files&dir=files/public&subDi ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

Adding a JSON array into a Postgres JSON column []

What is the proper way to insert the array ["a","b","c"] into a table named test? create table test( f json [] ); I attempted to do this using the following syntax: insert into test (f) values('{\"a\",\"b\",\"c\"}&apos ...

Problem with sending a form using Ajax

I've set up a page that dynamically generates a list of items. Each item in the list includes a button to submit a form with data specific to that item (the sorting is working correctly). The form submission is handled by the following jQuery code: & ...

Having trouble extracting the video ID from a Youtube feed XML with jQuery

My goal here is quite simple - I have created a search result using a URL string with the YouTube API. When you visit the URL, you can view the XML returned without any issues. The specific URL is: https://gdata.youtube.com/feeds/api/videos?q=all the smal ...

Exploring the jQuery syntax within Twitter Bootstrap JS files

Questioning the syntax used in Twitter Bootstrap's JS files. Take for example this snippet from bootstrap-dropdown.js: !function ($) { /* ... */ /* Querying the Standard Dropdown Elements -- Inquiry Code * ================================= ...

Parsing a path parameter and a JSON request body simultaneously within a method

Encountering an error when my method is structured like this @POST @Path("/share") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response shareit(@PathParam("USERID") String userID,Map<String,String[ ...

The header menu is not appearing on the gray bar in Internet Explorer

Having some issues with IE8, specifically on the website . The website header is not displaying correctly in IE8, but it works fine in Chrome and Firefox. Another issue is that the white area of the site is not 960px width as intended... ...