BarChart.vue 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <template>
  2. <div :class="className" :style="{height:height,width:width}"></div>
  3. </template>
  4. <script>
  5. import echarts from "echarts";
  6. require("echarts/theme/macarons"); // echarts theme
  7. import { debounce } from "@/utils";
  8. const animationDuration = 6000;
  9. export default {
  10. props: {
  11. className: {
  12. type: String,
  13. default: "chart"
  14. },
  15. width: {
  16. type: String,
  17. default: "100%"
  18. },
  19. height: {
  20. type: String,
  21. default: "380px"
  22. },
  23. title: {
  24. type: String,
  25. default: "chart"
  26. },
  27. options: {
  28. type: Object,
  29. default: function() {
  30. return {};
  31. }
  32. }
  33. },
  34. data() {
  35. return {
  36. chart: null,
  37. chartOptions: {}
  38. };
  39. },
  40. mounted() {
  41. this.initChart();
  42. this.__resizeHanlder = debounce(() => {
  43. if (this.chart) {
  44. this.chart.resize();
  45. }
  46. }, 100);
  47. window.addEventListener("resize", this.__resizeHanlder);
  48. },
  49. beforeDestroy() {
  50. if (!this.chart) {
  51. return;
  52. }
  53. window.removeEventListener("resize", this.__resizeHanlder);
  54. this.chart.dispose();
  55. this.chart = null;
  56. },
  57. created() {},
  58. watch: {
  59. options: function() {
  60. this.chartOptions = this.options;
  61. this.initChart();
  62. this.__resizeHanlder = debounce(() => {
  63. if (this.chart) {
  64. this.chart.resize();
  65. }
  66. }, 100);
  67. window.addEventListener("resize", this.__resizeHanlder);
  68. }
  69. },
  70. methods: {
  71. initChart() {
  72. console.log("this.chartOptions", this.chartOptions);
  73. this.chart = echarts.init(this.$el, "macarons");
  74. this.chart.setOption({
  75. title: {
  76. text: this.title
  77. },
  78. tooltip: {
  79. trigger: "axis",
  80. axisPointer: {
  81. // 坐标轴指示器,坐标轴触发有效
  82. type: "shadow" // 默认为直线,可选为:'line' | 'shadow'
  83. }
  84. },
  85. grid: {
  86. left: "2%",
  87. right: "2%",
  88. bottom: "3%",
  89. containLabel: true
  90. },
  91. xAxis: [
  92. {
  93. type: "category",
  94. data: this.chartOptions.xAxis,
  95. axisTick: {
  96. alignWithLabel: true
  97. }
  98. }
  99. ],
  100. yAxis: [
  101. {
  102. type: "value",
  103. axisTick: {
  104. show: false
  105. }
  106. }
  107. ],
  108. series: [
  109. {
  110. name: "",
  111. type: "bar",
  112. stack: "vistors",
  113. barWidth: "60%",
  114. data: this.chartOptions.series,
  115. animationDuration
  116. }
  117. ]
  118. });
  119. }
  120. }
  121. };
  122. </script>