The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data.

My initial suspicion is that maybe the options are not being passed for the lines, but it seems like dataCollection is not being populated, similar to every other type of chart. I am fairly new to Vue (only a few hours of experience), so it could be related to updating the state?

Languages.js

import { Line, mixins } from 'vue-chartjs'
//const { reactiveProp } = mixins

export default {
  extends: Line,
  //mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options)
  }
}

StatsSection.vue

<template>
<!-- Stats Section -->
<div class="stats-wrapper" style="margin: 15px 0; padding: 15px;">
  <languages :chart-data="datacollection"></languages>
</div>
</template>

<script>
import Languages from './charts/Languages.js'

export default {
  components: {
    Languages
  },
  data() {
    return {
      datacollection: {}
    }
  },
  mounted() {
    this.fillData()
  },
  methods: {
      fillData () {
        this.datacollection = {
          labels: [80, 12],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [40, 60]
            }, {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [72, 43]
            }
          ]
        }
      }
    }
}
</script>

Answer №1

The reason for this issue is due to the fillData() method being called in the mounted hook of your code. When the chart is initially rendered, it uses an empty data object which results in an empty chart.

Since chart.js is not reactive, the data is only filled after the chart has been rendered, causing the chart to remain empty.

Possible Solutions:

  • Provide a pre-filled data object to the chart instead of relying on the fillData method
  • Alternatively, consider incorporating the reactiveProp mixin into your code

Answer №2

After realizing that the gridlines were not displaying because I forgot to pass options for them, everything started making sense. The example code I was following assumed that the options were already set, which led to my confusion.

Languages.js

import {
  Bar,
  mixins
} from 'vue-chartjs'

export default {
  extends: Bar,
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  data() {
      return {
          options: { 
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero: true
                      },
                      gridLines: {
                          display: true
                      }
                  }],
                  xAxes: [{
                      gridLines: {
                          display: false
                      }
                  }]
              },
              legend: {
                  display: true
              },
              responsive: true,
              maintainAspectRatio: false
          }
      }
  },
  mounted() {
      this.renderChart(this.chartdata, this.options)
  }

}

Answer №3

To fix the issue, make sure to invoke your fillData() function inside the created(){..here...} hook rather than in the mounted(){} hook within your StatsSection.vue file. By doing this, the created hook will be executed before mounted, ensuring that your datacollection variable is not null during the initial load.

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

Experimenting with Vue in conjunction with a web component

I am facing an issue with astrouxds web components in my application. During testing, I am receiving a warning that needs to be resolved. Additionally, I need help on how to properly assert a value in the web component. console.error node_modules/vue/dis ...

Issues with Rails not successfully sending AJAX data to the controller

I am new to AJAX, so please bear with me while I try to figure this out. My goal is to send data from a chat message box to two places – the chat box itself and to a method in my Rails backend. This way, I can display the message in real-time and also st ...

Is there a way to retrieve the parent window's domain in a child window (opened with window.open) when both windows are located on different

Can anyone offer assistance with cross-domain communication between windows? Looking to use window.open(); function. ...

Images that adjust to different screen sizes within a grid layout

I have four images that need to be aligned in the following layout: ____________ |1 |4 | |_____| | |2 |3| | |__|__|______| They must be flush against each other, occupy 100% of the viewport's width, and most importantly, be respon ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

Is it possible to retrieve data from the server in Node.js/Vuetify based on a specific time frame?

I'm currently using a node.js server for my vuetify project. Within the server, I am parsing a csv file that contains scheduling and time information. Is there a method in my vuetify project to retrieve data from the csv file based on the current time ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Troubleshooting Problems with POST Requests in ExpressJS

Currently, I am working on developing a feature in NodeJS that allows users to upload files. However, I am encountering difficulties while attempting to make a simple POST request. In my index.ejs file, I have written code that generates a form and initia ...

Sorting Columns in JQuery Datatables

Encountering an issue with JQuery DataTables (datatables.net) where it takes 2 clicks to sort the columns when there are only 2 rows in the table. The first column sorts on the first click, but subsequent columns require multiple clicks. Despite testing th ...

What steps should I take to verify the validity of an Angular form?

I am struggling with validating an inscription form in HTML. Despite trying to implement validations, the inputs are still being saved in the database even when they are empty. Here are the validations I want to include: All inputs are required Email addr ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Implement a hover effect on a specific class targeting a nested element using JavaScript

Is there a method to apply a class that modifies rules for a child element using Javascript? I have successfully added it with CSS but am struggling to do the same with Javascript. Removing the class in JS is easy by referencing the classname before the ho ...

Using Vue.js to pass a variable from a parent component to a child component

Parent component: ShowComment Child component: EditComment I'm attempting to pass the value stored in this.CommentRecID to the child component. In the template of ShowComment, I have included: <EditComment CommentRecID="this.CommentRecID" v-if= ...

Replacing the yellow autofill background

After much effort, I have finally discovered the ultimate method to remove autofill styling across all browsers: $('input').each(function() { var $this = $(this); $this.after($this.clone()).remove(); }); However, executing t ...

Authentication failed due to Bcrypt.compare() returning invalid credentials

const express = require('express'); const router = express.Router(); const auth = require('../../middleware/auth'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const config = require(&apo ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

Using transition-group without the need to enclose it in a span tag

My goal is to add a transition effect to a Vuetify v-data-table, specifically when deleting a tbody element so that it fades out instead of abruptly disappearing from the screen. When I use a transition-group wrapping the tbody, the fade-out effect works a ...