The Vue ChartJS fails to display properly after the page is refreshed

Although this issue may appear to be a common one, some of the suggested solutions are outdated or no longer functional. My objective is to ensure that the chart remains responsive even after the page reloads. I attempted to implement the solution provided on the Vue website by incorporating watchers and mixins, but unfortunately, it did not yield the desired outcome. Several others, facing similar challenges, have also expressed their inability to render the chart upon refreshing the page.

Dashboard.vue

<template>
   <div align="center">
              <LineChart :chartData="chartData" :options="options" style="width:auto;height:auto;" />
            </div>
</template>
<script>
export default {
  data() {
    return {
      chartData: {
        labels: [],
        datasets: [
          {
            data: [],
            backgroundColor: "#3498db",
            borderColor: "rgba(136,136,136,0.5)",
            label: "",
          },
        ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        title: {
          display: true,
          text: "Student's Score Chart",
        },
        tooltips: {
          mode: "index",
          intersect: false,
        },
        hover: {
          mode: "nearest",
          intersect: true,
        },
        scales: {
          xAxes: [
            {
              display: true,
              scaleLabel: {
                display: true,
                labelString: "Student Names",
              },
            },
          ],
          yAxes: [
            {
              display: true,
              scaleLabel: {
                display: true,
                labelString: "Score Points",
              },
            },
          ],
        },
      },
   mounted() {
    this.getListData();
  },
   methods: {
      getListData() {
      axios
        .get("http://localhost/MyComposer/", {
          params: {
            answerId: 6,
            token: this.token,
          },
        })
        .then((response) => {
          console.log(response.data);
          for (var k = 0; k < response.data.length; k++) {
            const fullName =
              response.data[k].FirstName +
              " " +
              response.data[k].MiddleName +
              " " +
              response.data[k].LastName;

            this.chartData.labels.push(
              fullName + " (" + response.data[k].TestName + ") "
            );
            this.chartData.datasets[0].data.push(response.data[k].Score);
            console.log(this.chartData);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
}
}

ChartContainer.js

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

export default {
  extends: Line,
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  mounted () {
    this.renderChart(this.chartData, this.options)
  },
  watch: {
    chartData () {
      this.renderChart(this.chartData, this.options)
    }
  }
}

Answer №1

The solution to the problem was right there in the documentation all along. For those of you who were unaware, simply adding v-if will allow the mounted method to only activate once the page has fully loaded.

   <line-chart
                v-if="loaded"
                :chart-data="this.chartData"
                :options="this.options"
                style="width:auto;height:auto;"
              ></line-chart>

data: {
loaded: false 
}

getListData(){
   this.loaded = true;
 //My Axios API Request
}

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

When using selenium-python, every attempt to click a button consistently results in an error message

I've been trying to use Python-Selenium binding to click a button, but I haven't had any luck with various selectors so far. I'm currently using Chromedriver. Although I can select an element using elem = driver.find_element(by='xpath& ...

V-Stepper Slot Header in Vuetify 3 - Elevate Your Stepper

In the realm of creating a v-stepper in Vuetify 3, there exist two primary methods. One can either utilize the properties or delve into the template/slots. Personally, I encountered an issue with the properties method where the transition got all jumbled ...

Working with the visibility of a button using JavaScript

My goal is to toggle the visibility of a button using JavaScript. Initially, on page load, the button should be hidden. function hideButton(){ var x = document.getElementById('myDIV'); x.style.display = 'none'; } The visibilit ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...

Difficulty in comparing passwords using bcrypt encryption method

As a beginner in express js, I have successfully implemented the register functionality in my app. However, I am facing an issue with the login process. I am trying to compare the password stored in the database with the one provided by the user using bcry ...

What is the process for deducting the ordered quantity from the available quantity once an order is confirmed

Although I'm not a fan of hard coding, I've been struggling to find a solution to my problem and some explanations are just not clicking for me. The issue at hand involves three data products in the cart, product details, and placed order data f ...

Customize the CSS for material-ui buttons or create a new style altogether

Looking to customize the background color of a material UI RaisedButton, I have encountered a challenge. This is what I currently have: const style = { backgroundColor: 'green' }; export default class CreateLinksave extends React.Component { ...

Delete any classes that start with a specific prefix

Within my code, there is a div that holds an id="a". Attached to this div are multiple classes from different groups, each with a unique prefix. I am uncertain about which specific class from the group is applied to the div in JavaScript. My goal is to r ...

Is it possible to mimic a ref attribute with jest/rtl within a functional component?

I'm currently facing an issue with a functional component that includes a helper function. function Component() { imgRef = useRef(null) function helperFunction(node, ref) { if (!ref || !ref.current) return; ...do someth ...

Updating State Array dynamically with React JS

I am facing an issue with updating a UseState quantity array in real time. When clicking on a button, a new array is created with updated values for a specific object's quantity. However, the original array does not update immediately. Instead, it onl ...

Issues persist with $.getJSON

I apologize if this question has been addressed previously, but I couldn't find the answer I was seeking. My issue involves using $.getJSON to send variables to a PHP file. Although the file returns success as true, it always triggers the .fail functi ...

"Troubleshooting problem with fetching JSON data for Highcharts

As a relative newcomer to web development, my usual focus is on server-side work. Currently, I'm diving into a fun little electronic project where a Netduino server handles JSON requests within my LAN. The JSON response format from the Netduino looks ...

Steps for transferring a checked statement from an HTML document to a JavaScript file

Struggling to transfer checked statements from HTML to JS file {{#each readValues }} <br> Plug: {{@index}} => {{this}} <input type='checkbox' class="plug" onclick="sendData();" /> {{/each}} The code above is written i ...

Transferring information to React (Native) hooks in a way similar to how it is done

Transitioning to Hooks in React Native has been a new learning curve for me, especially when it comes to passing data to child elements. In the past with class-based components, passing props was as simple as using XML-style syntax. A Simple Example using ...

Having trouble getting the auto complete feature to work in AngularJS with jQuery

I have been attempting for the last 5 hours without any success... Below is the code snippet: Within View: <input type="text" ng-model="foo" auto-complete/>Foo = {{foo}} Inside the controller: myapp.directive('autoComplete', functi ...

Please provide both an image and text in addition to a progress bar by using the form to

I am working on a form that needs to store both images and text data in a database. <form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm"> <input name="name" type="text" /> <input name="age" ty ...

Exploring the power of the JavaScript this keyword

Can you explain the purpose of the line this.tasks = tasks; in relation to the constructor method? class TaskCollection { constructor(tasks =[]) { this.tasks = tasks; } } ...

Updating elements within a subarray in JavaScript can easily be accomplished by accessing the

I need help updating nested array elements in JavaScript. I want to convert dates into a different format. How can I update the nested elements? array1 = [ { "week": [ "2019-05-06T16:00:00.000Z", "2019-05-07T16:00:00.000Z", "2019-05-08T16:00:00.000Z", "20 ...

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...

Struggling with lag in MaterialUI TextFields? Discover tips for boosting performance with forms containing numerous inputs

Having some trouble with Textfield in my MateriaUI project. The form I created has multiple inputs and it's a bit slow when typing or deleting values within the fields. Interestingly, there is no lag in components with fewer inputs. UPDATE: It appear ...