index.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <template>
  2. <div
  3. style="height: 100%; width: 100%; position: absolute; left: 0; top: 0"
  4. class="ChartsBar"
  5. :id="id"
  6. ></div>
  7. </template>
  8. <script>
  9. import { markRaw } from "vue";
  10. import * as echarts from "echarts";
  11. import * as _ from "lodash";
  12. import { collectionStatistics } from "./echarts.js";
  13. // 柱状图初始数据
  14. export default {
  15. props: {
  16. // 柱状图生成所需id
  17. id: {
  18. type: String,
  19. default: "collection_ecahrt",
  20. },
  21. // 柱状图额外的数据
  22. option: {
  23. type: Object,
  24. default: () => {},
  25. },
  26. },
  27. data() {
  28. return {
  29. myChart: null, //柱状图实例
  30. };
  31. },
  32. mounted() {
  33. // 柱状图dom
  34. const chartDom = document.getElementById(this.id);
  35. // 柱状图初始化
  36. this.myChart = markRaw(echarts.init(chartDom));
  37. collectionStatistics.xAxis.data = this.option.time;
  38. collectionStatistics.series[0].data = this.option.data1;
  39. collectionStatistics.series[1].data = this.option.data2;
  40. // collectionStatistics.series[1].name = this.option.kg;
  41. // collectionStatistics.legend.data[1] = this.option.kg;
  42. collectionStatistics.yAxis[0].name = this.option.kg;
  43. // 生成柱状图
  44. this.myChart.setOption(collectionStatistics);
  45. // 监听页面缩放 防止dom重复渲染
  46. window.addEventListener("resize", _.debounce(this.handle, this.desc));
  47. },
  48. watch: {
  49. // 监听数据变化,重绘折线图
  50. option: {
  51. deep: true,
  52. handler(newVal) {
  53. const chartDom = document.getElementById(this.id);
  54. // 先移除之前的实例,保证重绘的流畅性
  55. // console.log(newVal, "11111");
  56. chartDom.removeAttribute("_echarts_instance_");
  57. this.myChart = markRaw(echarts.init(chartDom));
  58. collectionStatistics.xAxis.data = newVal.time;
  59. collectionStatistics.series[0].data = newVal.data1;
  60. collectionStatistics.series[1].data = newVal.data2;
  61. // collectionStatistics.series[1].name = newVal.kg;
  62. // collectionStatistics.legend.data[1] = newVal.kg;
  63. collectionStatistics.yAxis[0].name = newVal.kg;
  64. this.myChart.setOption(collectionStatistics);
  65. },
  66. },
  67. },
  68. destroyed() {
  69. // 销毁实例和移除监听
  70. this.myChart.dispose();
  71. window.removeEventListener("resize", this.handle);
  72. },
  73. methods: {
  74. /**
  75. * @description: 图形缩放
  76. * @param {*}
  77. * @return {*}
  78. */
  79. handle() {
  80. this.myChart.resize();
  81. },
  82. },
  83. };
  84. </script>
  85. <style lang="scss" scoped>
  86. .ChartsBar {
  87. background: #ffffff;
  88. }
  89. </style>