Refresh information in Chart.js in Vue.js upon hitting the submit button

I am currently working on a vuejs chart that displays data, and I have been trying to update the labels but it doesn't seem to be working.

Here's the code in ChartjsComponentLineChart.vue:

<script>
import { Line } from 'vue-chartjs'

export default {
  extends: Line,
  props: {
    data: {
      type: Object,
      default: null,
    },
    options: {
      type: Object,
      default: null,
    },
    plugins: {
      type: Array,
      default: null,
    },
    styles: {
      type: Object,
      default: null,
    },
  },
  mounted() {
    this.renderChart(this.data, this.options, this.plugins, this.styles)
  },
}
</script>

In report.vue

<b-card-body>
    <chartjs-component-line-chart
      :height="400"
      :data="data"
      :options="options"
      :plugins="plugins"
    />
  </b-card-body>

 <b-button
    variant="primary"
    class="btn-tour-finish"
    @click="submitData"
    >Submit
</b-button>



data() {
  return: {
     data: {
        labels: [],
        datasets: [
          {
            data: [70, 95, 100, 120, 257, 271, 300, 321, 383, 450],
            label: "Supper",
            borderColor: "#3e95cd",
          },
        ],
      },
      options: {
        title: {
          display: true,
          text: "Report",
        },
        responsive: true,
        maintainAspectRatio: false,
      },
  }
},
created() {
    this.data.labels = [1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025];
  },
methods: {
   submitData() {
     this.data.labels = [1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025, 2030];
  }
}

The chart is displaying correctly. However, when I click on the submit button (submitData()), the labels do not update. Can you provide any suggestions on how to update the 'labels' when the button is clicked? Thank you!

Answer №1

Chart.js does not have built-in reactivity, requiring manual use of the update method when data changes. However, vue-chartjs takes on this non-reactive behavior by default.

To enable reactivity, you must incorporate the reactiveProp mixin into your lineChart component as outlined in the documentation.

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

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // Chart data is generated within the mixin.
    // To pass options, create a local options object
    this.renderChart(this.chartData, this.options)
  }
}

If desired, you can create your own watcher to manually update chart.js by referring to the documentation.

watch: {
  data () {
    this.$data._chart.update()
  }
}

Answer №2

I successfully resolved the issue by using this method: v-if="loaded"

<b-card-body>
    <chartjs-component-line-chart
      v-if="loaded"
      :height="400"
      :data="data"
      :options="options"
      :plugins="plugins"
    />
  </b-card-body>

data() {
  return: {
     data: {
        loaded: false,
        labels: [],
        datasets: [
          {
            data: [70, 95, 100, 120, 257, 271, 300, 321, 383, 450],
            label: "Supper",
            borderColor: "#3e95cd",
          },
        ],
      },
      options: {
        title: {
          display: true,
          text: "Report",
        },
        responsive: true,
        maintainAspectRatio: false,
      },
  }
},
created() {
    this.data.labels = [1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025];
    this.loaded = true;
  },
methods: {
   submitData() {
     this.data.labels = [1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025, 2030];
     this.loaded = true;
  }
}

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

Using Vue and vue-multiselect to create interactive options based on the selected language

I'm currently developing a Vue website with multilingual support. The chosen language is stored in a Vuex store and accessed through the computed property lang, like so: lang(){ return this.$store.state.lang } I use this lang property in v-if cond ...

The prolonged action is causing the renderer process to become locked

I am currently experiencing an issue with a function that is triggered by changes in a vue-select component within my component template. <v-select v-model="model" :options="eventList" :placeholder="currentEventTitle" v-on:input="selectedEvent" ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

Issue: The vue-loader module needs @vue/compiler-sfc to be included in the dependency tree

Encountering an issue while attempting to execute the following command: npm run serve I have attempted to resolve this by running npm update and sudo npm serve, without success. Additionally, deleting the package-lock.json file and then running npm insta ...

Using Vue.js: Passing an object from data() to a mounted() function

I'm facing an issue while attempting to pass the grid array to the createGridChart. An error message stating "grid is not defined" keeps popping up: “grid is not defined”. export default { data() { return { grid: [], } ...

Having trouble uploading custom fonts to my Vue application using SASS

Currently utilizing the sass loader in my vue app (using vue CLI 3) for styling. However, I encountered an error when attempting to load local fonts in one of my scss files, stating "This relative module was not found." To simplify things, I placed my font ...

Sorry, there was an error with Vue-i18n: Unable to access the 'config' property because it is undefined

Let's start by examining what functions correctly in App.js import router from './routes.js'; import VueI18n from 'vue-i18n'; const messages = { en: { message: { hello: 'hello world' } } } // Create ...

Issue with Axios Response Interceptor on Vuejs causing failure to pass response data

axios.interceptors.response.use( (response) => { return response }, async (error) => { const instance = axios.create({ baseURL: 'myrestbase', timeout: 1000, headers: { 'Authorization': 'Bearer T ...

The issue with the v date picker is that it is not triggering the change event when a single

I am having some trouble detecting the change event of a date picker. It was working perfectly when the user selected multiple days from the calendar, but if they only select a single date, the change method does not get triggered. Here is my attempt: < ...

Managing timeouts and errors in a Spring and Vue login systemIn this system,

I am currently working on developing a back-end using Spring and a front-end with Vue. Both projects are separate but running on the same machine. I have managed to resolve or disable all cors, csrf, and login issues except for one that has left me complet ...

Looping through components using the render template syntax in Vue3

Below is my Vue3 code snippet: <template> {{click}} <ol> <li v-for="item in items" :key="item" v-html="item"></li> </ol> </template> <script setup> const click = ref(); const items = ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

Creating a Vue Directive in the form of an ES6 class: A step-by-step

Is it possible to make a Vue directive as an ES6 Class? I have been attempting to do so, but it doesn't seem to be working correctly. Here is my code snippet: import { DirectiveOptions } from 'vue'; interface WfmCarriageDirectiveModel { ...

Error message: "Vue-i18n is not defined in the vuex

I've been attempting to update the locale in my Vue project using Vuex and VueI18n. Initially, I thought I had figured out a way to update the locale by setting the i18n value in the store object and then using it like this (mutation): UPDATE_LAN ...

unable to store user input in a REST API using the store functionality

Welcome to my main page! Here, I have a form that I am looking to connect with an API in order to store the entered data: <div> <span>User ID</span> <input type="text" v-model="info.userId"> </div> <br> <div> ...

Iterating through and dispatching to the modal窶ヲ

Can someone help me figure out why I am encountering a problem where clicking on the button below results in seeing three different objects before being told that invoice is undefined? <tr :key="invoice" v-for="(invoice, index) in invoices"> & ...

Having trouble retrieving data from the payload within vuex actions

I am currently utilizing Vuex for state management. Here is my store.js file: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); export const store = new Vuex.Store({ state: { loggedIn : false }, getters: {}, mutations: ...

Exploring input in interactive table

Just started learning Vue.js and I could use some guidance! I'm attempting to add a Search input for each column to filter results for the user This is the code in my HTML file: <div id="table" > <div class=" cont ...

Passing data from child component to parent component using Vue emit

Having some trouble figuring out why this code isn't functioning as expected, despite following the same examples I've seen. Parent.vue <tree-select class="ml-5 tree-select" :nodes="all" :value=&q ...