I'm building a budget app with quasar. I'm trying to update the bar value of a chartjs BarChart with a q-slider. But the bar isn't updating when I submit the value. The 'income.value' gives me the correct value in the console. The income.value has the be in an array because the barchart needs te receive more values.
<template>
<div class="q-pa-md">
<q-form @submit="onSubmit" class="q-gutter-md">
<div class="q-mt-xl">
<q-slider
name="income"
v-model="income"
label-always
:min="0"
:max="10000"
:step="10"
/>
</div>
<div>
<q-btn label="Submit" type="submit" color="primary" />
</div>
</q-form>
<Bar id="my-chart-id" :options="chartOptions" :data="chartData" />
</div>
</template>
<script>
import { Bar } from 'vue-chartjs';
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale,
} from 'chart.js';
import { ref } from 'vue';
ChartJS.register(
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale
);
const income = ref(0);
export default {
name: 'BarChart',
components: { Bar },
setup() {
const chartData = ref({
labels: ['January'],
datasets: [{ data: [income.value] }],
});
const chartOptions = ref({
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 10000,
},
},
});
const onSubmit = () => {
console.log('Submitted Income Value:', income.value);
chartData.value.datasets[0].data = [income.value];
this.$data._chart.update();
};
return { income, chartData, chartOptions, onSubmit };
},
};
</script>
I'm trying to push the income.value to the dataset data array.
With the help of Yoduh, I found an answer for this, more like a short workaround. You need to reassign the entire dataset to update the chart after changes.
const updateChart = () => {
const newData = {
labels: ['Income', 'Expenditure', 'Savings'],
datasets: [{ data: [income.value, 1500, 250] }],
};
chartData.value = {
...chartData.value,
...newData,
};
};
```