EchartsCom.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // console.log(newVal, '2dbwquduiqh')
  51. if (this.myChart) {
  52. this.id = uid()
  53. this.$nextTick(() => {
  54. this.myChart.setOption(newVal)
  55. })
  56. }
  57. },
  58. deep: true // 深度监听,
  59. // immediate: true, //要立即监听
  60. }
  61. },
  62. mounted() {
  63. setTimeout(() => {
  64. window.addEventListener('resize', this.myChart)
  65. this.id = uid()
  66. this.initEcharts()
  67. }, 0)
  68. },
  69. created() {
  70. // 4.id赋值
  71. },
  72. methods: {
  73. initEcharts() {
  74. this.$nextTick(() => {
  75. const _this = this
  76. // 5. 创建echarts图表实例
  77. _this.myChart = echarts.init(document.getElementById(this.id))
  78. // 指定图表的配置项和数据
  79. const option = this.option
  80. // 使用刚指定的配置项和数据显示图表。
  81. _this.myChart.clear()
  82. const that = _this
  83. _this.myChart.setOption(option)
  84. window.onresize = function () {
  85. that.myChart.resize()
  86. }
  87. })
  88. }
  89. },
  90. destroyed() {
  91. window.removeEventListener('resize', this.myChart)
  92. }
  93. }
  94. </script>