Forrest Hong
Forrest Hong

Reputation: 1

How to call chart-zoom resetZoom function when char data changes?

I have a Vue project with following packages installed.

├── [email protected] ├── [email protected] ├── [email protected] ├── [email protected] └── [email protected]

I created a "LineChart.vue" components, what I want is that when the "chartData" was changed in parement, I want to call the "resetZoom" function provided in "chartjs-plugin-zoom" package.

How can I do this in vue-chartjs 5.2? it seems that since v4 version, the vue-chartjs have data change watcher and options change watcher by default. Wrapper will update or re-render the chart if new data or new options is passed. but how to hook the data change event in my component?

Contents of "LineChart.vue"

<template>
  <Line :data="chartData" :options="chartOptions"/> 
</template>
  
<script>
import zoom from 'chartjs-plugin-zoom';

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import { Chart, Line} from 'vue-chartjs'
import { watch, ref, reactive} from 'vue';
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  zoom
)

export default {
  name: 'LineChart',
  components: { Line },
  props: ['chartData', 'chartOptions'],
  setup(props) {
    console.log("LineChart  setup!");
  }
}
</script>

I tried to add a watcher on chartData, but seems it doesn't work. I am a new in Vue, any one can help on this?

export default {
  name: 'LineChart',
  components: { Line },
  props: ['chartData', 'chartOptions'],
  setup(props) {
    watch( () => props.chartData, (newValue, oldValue) => {
      console.log("watcher triggled fro chartData", newValue, oldValue);
    },
    { deep: true }
    )
    console.log("LineChart  setup!");
  },
  mounted () {
    console.log("PmaGroupLineChart  mounted!");
    
  }
}

Upvotes: 0

Views: 172

Answers (1)

Yitz
Yitz

Reputation: 1306

You need to set a ref in your chart to access it, and then call resetZoom() on that ref when data changes:

<Line :data="chartData" :options="chartOptions" ref="myLineChart"/> 
setup() {
    const myLineChart = ref(null);
    
    watch(
        () => props.chartData,
        () => {
            myLineChart.resetZoom();
        },
        { deep: true }
    );

    return { myLineChart };
}

See the Vue docs for more info on template refs.

Upvotes: 0

Related Questions