echartsEchar.vue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <template>
  2. <div :id="uuid" :style="style"></div>
  3. </template>
  4. <script>
  5. import * as echarts from "echarts";
  6. export default {
  7. props: {
  8. height: {
  9. type: String,
  10. default: "100%",
  11. },
  12. width: {
  13. type: String,
  14. default: "100%",
  15. },
  16. options: {
  17. type: Object,
  18. default: null,
  19. },
  20. widthHtval: {
  21. type: [String, Boolean],
  22. default: false
  23. },
  24. clickOnTheEvent: { // 是否开启点击事件
  25. type: [Boolean],
  26. default: false
  27. },
  28. updateChartSize: { // 是否需要自动更新图表的大小
  29. type: [Boolean],
  30. default: false
  31. }
  32. },
  33. components: {},
  34. data() {
  35. return {
  36. uuid: null,
  37. myChart: null,
  38. };
  39. },
  40. computed: {
  41. style() {
  42. return {
  43. height: this.height,
  44. width: this.width,
  45. };
  46. },
  47. },
  48. watch: {
  49. options() {
  50. if (this.myChart) {
  51. if (this.widthHtval) {
  52. this.myChart.resize({
  53. width: this.widthHtval
  54. })
  55. }
  56. this.myChart.setOption(this.options, { notMerge: true });
  57. if (this.updateChartSize) {
  58. this.$nextTick(() => {
  59. this.myChart.resize(); // 在DOM更新后,调用resize方法更新图表大小
  60. });
  61. }
  62. }
  63. },
  64. },
  65. created() {
  66. this.uuid = this.idGen();
  67. },
  68. mounted() {
  69. this.myChart = echarts.init(document.getElementById(this.uuid));
  70. this.myChart.setOption(this.options);
  71. if (this.clickOnTheEvent) {
  72. this.myChart.getZr().on('click', params => {
  73. this.$emit('chartClickEvents', { params, myChart: this.myChart })
  74. })
  75. }
  76. },
  77. methods: {
  78. // idGen() {
  79. // return new Date().getTime();
  80. // },
  81. idGen() {
  82. const arr = new Uint8Array(16);
  83. window.crypto.getRandomValues(arr);
  84. arr[6] = (arr[6] & 0x0f) | 0x40; // 设置版本为 0100
  85. arr[8] = (arr[8] & 0x3f) | 0x80; // 设置变体为 10xx
  86. return [...arr].map((b) => ('00' + b.toString(16)).slice(-2)).join('').match(/.{1,8}/g).join('-');
  87. },
  88. },
  89. beforeDestroy() {
  90. if (this.myChart) {
  91. this.myChart.dispose();
  92. }
  93. }
  94. };
  95. </script>
  96. <style scoped lang="scss"></style>