Dynamically changing chart types with Vue Chart.js

筅森魡賤 提交于 2020-04-30 10:23:06

问题


I'm trying to use Vue Chart.js to implement a chart selector to visualise various data.

Structure of application:

  • ChartPicker.vue (allow user to pick chart, create data, use dynamic component key to re-render component)
    • ChartWrapper.vue (receives props and passes them on, creates mixin for dynamic chart type)
      • ChartRender.vue (simply renders chart)

In the chart render component you usually you need to do 'extends: Bar', 'extends: Line' etc, therefore, requiring a ChartRender component type for each chart type. I found a neat solution that passes in the chart type to the chart mixins, then the final chart render makes no reference to chart type (not quite clear how this works even after looking at vue-chart.js code). This is the example I based my code on (it has no chart type selection):

https://codesandbox.io/s/vue-template-original-1czfi

So, I tried to extend functionality of that example to add a chart selector. It's working to an extent on chart type change: data changes, components re-render but the chart type doesn't change (even though it's being passed to the mixin dynamically)

I have a running example here:

https://codesandbox.io/s/vue-chart-issue-v2-twg3o

I've spent nearly a week trying to figure this out with no joy. I could create a workaround to use a separate ChartRender component for each chart type (e.g. ChartRenderBar, ChartRenderLine etc) but it moves away from DRY, so would rather not.

If anybody could help, I'd be VERY appreciative,


回答1:


in Vuejs, it is not possible to change mixins after the component being created, and because of this I've used a wrapper component in my other solution, so I can pass a mixin dynamically before the component being created, but unfortunately, there is no way to have some kind of reactive mixin.

my solution for you current situation would be something like that:
https://codesandbox.io/s/vue-template-y5wsw

in the above solution, I have created two components, BarChart and LineChart
to switch between those dynamically, I am using one of the most awesome features in vuejs, Dynamic Component

and of course to avoid duplicating the data source, you can use vuex to share data between multiple components, or you can have the data in the parent page and access your dataset or options like

this.$parent['whatever data property in your parent component']

Hope you found this helpful.



来源:https://stackoverflow.com/questions/60889447/dynamically-changing-chart-types-with-vue-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!