Vue-chartjs line chart not displaying data fetched from API

I successfully created bar charts using vue2 and vue-chart.js with data from an API call. However, I am facing issues with displaying line charts. Despite loading the data, the line chart is not showing up, and no errors are being displayed. I have reviewed my code but cannot identify the error. Any suggestions? Thanks!

https://i.sstatic.net/OqmZt.png

Versions:

"vue": "^2.6.11"
"vue-chartjs": "^4.1.1"

my base-vue:

<template>
        
          <div id="app" class="content">
        
            <div class="dist_30"></div>
            <h3>Charts</h3>
        
            <div class="dist_10"></div>
        
            <div class="row ">
        
              <div class="col-12">
        
                <div style="margin: 10px 10px 10px 10px;">
                  <BarChart />
                </div>
        
              </div>
        
            </div>
        
            <div class="row ">
        
              <div class="col-12">
        
                <div style="margin: 10px 10px 10px 10px;">
                  <LineChart />
                </div>
        
              </div>
        
            </div>
        
          </div>
        
        </template>
        
        <script>
        import BarChart from '@/components/BarChart'
        import LineChart from '@/components/LineChart'
        
        export default {
          name: 'App',
          components: { BarChart , LineChart}
        }
        </script>

my LineChart.vue:

<template>
          <Line v-if="loaded"
            :chart-options="chartOptions"
            :chart-data="chartData"
            :chart-id="chartId"
            :dataset-id-key="datasetIdKey"
            :plugins="plugins"
            :css-classes="cssClasses"
            :styles="myStyles"
            :width="300"
            :height="height"
          />
        </template>
        
        <script>
        import { Line } from 'vue-chartjs/legacy'
        import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, LineElement, CategoryScale, LinearScale } from 'chart.js';
        
        ChartJS.register(Title, Tooltip, Legend, BarElement,  LineElement, CategoryScale, LinearScale);
        
        const chartAPI = 'https://m.myapp2go.de/services/getstatistik_tables.php';
        
        export default {
          
          name: 'LineChart',
          components: { Line },
        
            async mounted () {
            this.loaded = false
        
            try {
        
              const response = await fetch(chartAPI);
              const chartArray = await response.json();
              this.chartdata = chartArray.items;
        
                // Get all the numbers/labels from the response
                  this.chartData.labels = this.chartdata.map(i => i.table).slice(1); 
                  this.chartData.datasets[0].data = this.chartdata.map(i => i.count).slice(1); 
        
                  console.log("chart Data ", JSON.stringify(this.chartdata));
                  console.log("chart Data numbers: ", this.newChartArray);
        
                  this.loaded = true
        
            } catch (e) {
              console.error(e)
            }
          },
            computed: {
            myStyles () {
              return {
                position: 'relative'
              }
            }
          },
          props: {
            chartId: {
              type: String,
              default: 'line-chart'
            },
            datasetIdKey: {
              type: String,
              default: 'label'
            },
            width: {
              type: Number,
              default: 200
            },
            height: {
              type: Number,
              default: 0
            },
            cssClasses: {
              default: '',
              type: String
            },
            styles: {
              type: Object,
              default: () => {}
            },
            plugins: {
              type: Array,
              default: () => []
            }
          },
          data() {
            return {
              chartData: {
                labels: [ 'num', 'call', 'blog', 'key', 'mod,' ,'pic', 'acc', 'ifc', 'req', 'inf' ],
                datasets: [ { 
                  label: 'Database statistics',
                  borderWidth: 1,
                  
                  data: [ ]} ]
              },
              chartOptions: {
                responsive: true,
                maintainAspectRatio: false
              },
              newChartArray: [],
              loaded: false
            }
          }
        }
        </script>

output from chrome-dev-tools:

<Line chart-options="[object Object]" chart-data="[object Object]" chart-id="line-chart" dataset-id-key="label" plugins="" css-classes="" styles="[object Object]" width="300" height="0"></Line>

Answer №1

To ensure that both the Bar chart and Line chart work correctly, it is necessary to import specific components in the following manner:

import { Line as LineChartGenerator } from 'vue-chartjs/legacy'

import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    LineElement,
    LinearScale,
    CategoryScale,
    PointElement
} from 'chart.js'

ChartJS.register(
    Title,
    Tooltip,
    Legend,
    LineElement,
    LinearScale,
    CategoryScale,
    PointElement
)

Additionally, for the template, make sure to include the following:

<LineChartGenerator v-if="loaded"
            :chart-options="chartOptions"
            :chart-data="chartData"
            :chart-id="chartId"
            :dataset-id-key="datasetIdKey"
            :plugins="plugins"
            :css-classes="cssClasses"
            :styles="myStyles"
            :width="300"
            :height="height"
          />

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

Send the user to the codeigniter controller with a click

Is there a way to redirect a user to a different page when they click on a specific division element? I am looking for guidance on how to redirect the user to CI's new controller from an HTML view. Thank you in advance. ...

What is the process for selecting and accessing a DOM element?

Looking to utilize jQuery selector for accessing deep within the DOM. HTML <table> ...more here <tr> <td class="foo bar clickable"> <div> <div class="number">111</div> //Trying to retrieve "111" ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Is there a way to resize SVG images without having to modify the underlying source code?

Within my Vue Single File Component, there is a prop labeled svg, which holds a string of SVG markup like <svg>...</svg>. What is the best way to render and resize this SVG content? ...

AJAX successfully completes, but no response is received

I've been struggling to get the success function in my AJAX call to trigger. I know everything is set up correctly because when I make a request to my API, I can see that it's hitting the URL and the server is responding with an HTTP 200 status. ...

Control Center for JavaScript Administration

When dealing with Javascript content on a larger website, what is the best way to efficiently manage it? I am facing challenges with multiple $(document).ready()'s and the need to handle numerous id strings ($('#id')). One idea was to combin ...

Laravel encounters an issue when trying to access the user ID

I am currently working on a project using Laravel and Vue. I'm trying to pass the user ID to the table when the user is authenticated, but I'm facing an issue where the authenticated user's ID is not being passed to the query, resulting in t ...

Guide to integrating custom fields in Wordpress with mapbox-gl js to generate map markers

Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...

What is the best way to include an image link in a JSON file using Nuxt.js?

I am working with nuxtjs and I have a file named data.json in the root directory. I am trying to add an image link in this JSON file, but it is not recognizing it. Here is my code: { "id": 1, "cardImg": "./assets/images/ima ...

Is there a way to have the collapsible content automatically expanded upon loading?

I came across a tutorial on w3school (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol), which demonstrates collapsible content hidden by default. The code snippet from the link is provided below. Can someone assist me in cha ...

Non-reactive behavior observed in Parent Object upon deletion of Child Array element

In the employee array, I have data for both children and spouse. However, I am facing an issue where if I delete the children array, the employee data does not update reactively as expected. ...

Spontaneous gradient background occasionally failing to load as expected

My to-do list is simple and functional, but I'm encountering an unusual issue with the background. The background is supposed to be a random gradient set using JS upon loading the HTML, but sometimes it doesn't apply at all. If you refresh the Co ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

Can anyone suggest a solution to troubleshoot this issue with CSS Flexbox and absolute positioning?

I'm currently developing a React application featuring flex container cards (referred to as .FilmCard with movie poster backgrounds) within another flex container with flex-wrap. Each card has an item positioned absolutely (an FontAwesome arrow icon). ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

Are there any conventional methods for modifying a map within an Aerospike list?

Attempting to modify an object in a list using this approach failed const { bins: data } = await client.get(key); // { array: [{ variable: 1 }, { variable: 2 }] } const { array } = await client.operate(key, [Aerospike.maps.put('array', 3).withCon ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

Retrieving the response data from a jQuery AJAX call prior to executing the success function

I have a system that relies on AJAX calls through jQuery for data retrieval. My goal is to capture all the received data along with the request details, without altering the existing $.ajax implementations, and forward it to another API for further analysi ...

Troubleshooting the error message "XMLHttpRequest cannot load" when using AngularJS and WebApi

I have developed an asp.net webApi and successfully published it on somee.com. When I access the link xxxx.somee.com/api/xxxx, everything works fine. However, when I try to call it in Angularjs, it does not work. $http.get('http://xxxxxx.somee.com/ap ...

Node.js server experiencing delays due to V8 processing constraints

REVISED I am currently running a nodeJS http server designed to handle uploads from multiple clients and process them separately. However, I have encountered an issue where the first request seems to block any subsequent requests until the first one is co ...