Skip to content

Commit 5cc8f0a

Browse files
author
Spencer Dellis
authored
Resolve reactivity mixin animation issue.
A small consequence of replacing the entire dataset in the [reactive mixins files](https://github.com/apertureless/vue-chartjs/blob/develop/src/mixins/reactiveData.js) is that it causes charts to completely re-render even if only the 'data' attribute of a dataset is changing. In my case, I set up a reactive doughnut chart with two data points but whenever the data values change, instead of shifting the fill coloring, it completely re-renders the entire chart. You can see the issue in this fiddle (the problem remains even when changing chart type): https://jsfiddle.net/sg0c82ev/11/ To solve the issue, I instead run a diff between the new and old dataset keys, remove keys that aren't present in the new data, and update the rest of the attributes individually. After making these changes my doughnut chart is animating as expected (even when adding and removing new dataset attributes). A fiddle with my changes: https://jsfiddle.net/sg0c82ev/12/ Perhaps this is too specific of a scenario to warrant a complexity increase (and better suited for a custom handler) but I figured it would be better to dump it here and make it available for review. Let me know what you think.
1 parent b762d40 commit 5cc8f0a

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

src/mixins/reactiveData.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,26 @@ module.exports = {
2626
// Check if Labels are equal and if dataset length is equal
2727
if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) {
2828
newData.datasets.forEach((dataset, i) => {
29-
chart.data.datasets[i] = dataset
29+
// Get new and old dataset keys
30+
const oldDatasetKeys = Object.keys(oldData.datasets[i])
31+
const newDatasetKeys = Object.keys(dataset)
32+
33+
// Get keys that aren't present in the new data
34+
const deletionKeys = oldDatasetKeys.filter((key) => {
35+
return key !== '_meta' && newDatasetKeys.indexOf(key) === -1
36+
})
37+
38+
// Remove outdated key-value pairs
39+
deletionKeys.forEach((deletionKey) => {
40+
delete chart.data.datasets[i][deletionKey]
41+
})
42+
43+
// Update attributes individually to avoid re-rendering the entire chart
44+
for (const attribute in dataset) {
45+
if (dataset.hasOwnProperty(attribute)) {
46+
chart.data.datasets[i][attribute] = dataset[attribute]
47+
}
48+
}
3049
})
3150

3251
chart.data.labels = newData.labels

0 commit comments

Comments
 (0)