4👍
The Chart.js docs indicate that you can push new data into the chart’s data.datasets[]
and data.labels
properties, and then calling chart.update()
:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
PrimeVue’s Chart
component exposes the underlying Chart.js instance via chart
, so you can use that property update the chart:
-
Apply a template ref on the
Chart
component:<Chart ref="primeChart">
import { ref } from 'vue' export default { setup() { const primeChart = ref() // chart.js instance is now available via primeChart.value.chart return { primeChart, } } }
-
Return the chart data from
setup()
(i.e., use the Composition API to avoid making the bound array data reactive). This is necessary to avoid aMaximum call stack size exceeded
error when modifying the chart data.export default { setup() { return { // non-reactive data basicData: {/*...*/}, basicOptions: {/*...*/}, } } }
-
Create an
addData
method that updates the chart.js instance (via the template ref), following the example from the Chart.js docs above:export default { setup() { const primeChart = ref() const addData = () => { const chart = primeChart.value.chart chart.data.labels.push(/* NEW DATA LABEL */) chart.data.datasets[0].data.push(/* NEW DATA VALUE */) chart.update() } } }
Now you can use
addData()
(e.g., through a button click) to update the chart with new data.