BaseCharts.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import Chart from 'chart.js'
  2. export function generateChart (chartId, chartType) {
  3. return {
  4. render: function (createElement) {
  5. return createElement(
  6. 'div', {
  7. style: this.styles,
  8. class: this.cssClasses
  9. },
  10. [
  11. createElement(
  12. 'canvas', {
  13. attrs: {
  14. id: this.chartId,
  15. width: this.width,
  16. height: this.height
  17. },
  18. ref: 'canvas'
  19. }
  20. )
  21. ]
  22. )
  23. },
  24. props: {
  25. chartId: {
  26. default: chartId,
  27. type: String
  28. },
  29. width: {
  30. default: 400,
  31. type: Number
  32. },
  33. height: {
  34. default: 400,
  35. type: Number
  36. },
  37. cssClasses: {
  38. type: String,
  39. default: ''
  40. },
  41. styles: {
  42. type: Object
  43. },
  44. plugins: {
  45. type: Array,
  46. default () {
  47. return []
  48. }
  49. }
  50. },
  51. data () {
  52. return {
  53. _chart: null,
  54. _plugins: this.plugins
  55. }
  56. },
  57. methods: {
  58. addPlugin (plugin) {
  59. this.$data._plugins.push(plugin)
  60. },
  61. generateLegend () {
  62. if (this.$data._chart) {
  63. return this.$data._chart.generateLegend()
  64. }
  65. },
  66. renderChart (data, options) {
  67. if (this.$data._chart) this.$data._chart.destroy()
  68. this.$data._chart = new Chart(
  69. this.$refs.canvas.getContext('2d'), {
  70. type: chartType,
  71. data: data,
  72. options: options,
  73. plugins: this.$data._plugins
  74. }
  75. )
  76. }
  77. },
  78. beforeDestroy () {
  79. if (this.$data._chart) {
  80. this.$data._chart.destroy()
  81. }
  82. }
  83. }
  84. }
  85. export const Bar = generateChart('bar-chart', 'bar')
  86. export const HorizontalBar = generateChart('horizontalbar-chart', 'horizontalBar')
  87. export const Doughnut = generateChart('doughnut-chart', 'doughnut')
  88. export const Line = generateChart('line-chart', 'line')
  89. export const Pie = generateChart('pie-chart', 'pie')
  90. export const PolarArea = generateChart('polar-chart', 'polarArea')
  91. export const Radar = generateChart('radar-chart', 'radar')
  92. export const Bubble = generateChart('bubble-chart', 'bubble')
  93. export const Scatter = generateChart('scatter-chart', 'scatter')
  94. export default {
  95. Bar,
  96. HorizontalBar,
  97. Doughnut,
  98. Line,
  99. Pie,
  100. PolarArea,
  101. Radar,
  102. Bubble,
  103. Scatter
  104. }