EchartsCom.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <template>
  2. <!-- 定义标签 -->
  3. <div
  4. v-resize="resize"
  5. :id="id"
  6. v-if="option"
  7. :style="{
  8. width: width,
  9. height: height,
  10. }"
  11. ></div>
  12. </template>
  13. <script>
  14. import { myMixin } from "@/mixins/echartsMixin";
  15. import * as echarts from "echarts";
  16. import "echarts/extension/bmap/bmap";
  17. // 2.生成一个 id 值给标签,目的是为了当多次使用组件防止id重复
  18. const uid = function () {
  19. return new Date().getTime();
  20. };
  21. export default {
  22. mixins: [myMixin],
  23. //1.获取传过来的值
  24. props: {
  25. width: {
  26. type: String,
  27. default: "",
  28. },
  29. height: {
  30. type: String,
  31. default: "",
  32. },
  33. option: {
  34. typeof: Object,
  35. default() {
  36. return {};
  37. },
  38. },
  39. },
  40. data() {
  41. return {
  42. //3.在这定义 id 与 myChart图表实例 , 方便管理
  43. id: null,
  44. myChart: null,
  45. };
  46. },
  47. watch: {
  48. option: {
  49. handler(newVal, oldVal) {
  50. if (this.myChart) {
  51. this.id = uid();
  52. this.$nextTick(() => {
  53. this.myChart.setOption(newVal);
  54. });
  55. }
  56. },
  57. deep: true, // 深度监听,
  58. // immediate: true, //要立即监听
  59. },
  60. },
  61. mounted() {
  62. setTimeout(() => {
  63. window.addEventListener("resize", this.myChart);
  64. this.id = uid();
  65. this.initEcharts();
  66. }, 0);
  67. },
  68. created() {
  69. // 4.id赋值
  70. },
  71. methods: {
  72. initEcharts() {
  73. this.$nextTick(() => {
  74. const _this = this;
  75. // 5. 创建echarts图表实例
  76. _this.myChart = echarts.init(document.getElementById(this.id));
  77. // 指定图表的配置项和数据
  78. const option = this.option;
  79. // 使用刚指定的配置项和数据显示图表。
  80. _this.myChart.clear();
  81. const that = _this;
  82. _this.myChart.setOption(option);
  83. window.onresize = function () {
  84. that.myChart.resize();
  85. };
  86. });
  87. },
  88. },
  89. destroyed() {
  90. window.removeEventListener("resize", this.myChart);
  91. },
  92. };
  93. </script>