Search code examples
vue.jsvuexvue-chartjs

How to update chart using mixin on state change?


I've mapped chartData to a state property using vuex. What I'd like to do is update the chart when a dataset is updated. The mixin automatically sets a watcher on chartData according to the documentation but I'm unsure how to use it with vuex.

LineChart.js:

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

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

MarketChart.vue:

<template>
  <div>
    <line-chart :chart-data=chartData :height=height :options=options></line-chart>
  </div>
</template>

<script>

import LineChart from "./LineChart.js";
import { mapGetters, mapState } from "vuex";

export default {
  components: {
    LineChart
  },
  data() {
    return {
      height: 200
    };
  },
  computed: {
    ...mapState({
      chartData: "chartData",
      options: "chartOptions"
    })
  }
};
</script>

The store data path is chartData.datasets[i].data.

The chart initially renders correctly and I know the data is correctly updated in the state (after updating the state, if I trigger hot reloading in development it re-renders the chart with the updated data) but the chart isn't updating. How can I use the mixin with mapped state variables or otherwise trigger an update on state change?


Solution

  • Depends on how you change the data. If only the data changes and not the labels it may be possible that the watcher does not recognize the change.

    Generally you can use vuex and vue-chartjs together without problems: Here is an example repo: https://github.com/apertureless/vue-chartjs-vuex

    However the vue-chartjs version is old. But the concept is the same.