echarts.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <template>
  2. <div class="hc-echarts-box">
  3. <div ref="echart" class="hc-echarts" :style="`width : ${chart?.clientWidth}px`" />
  4. </div>
  5. </template>
  6. <script setup>
  7. import * as echarts from 'echarts'
  8. import { getObjValue } from 'js-fast-way'
  9. import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
  10. const props = defineProps({
  11. option: {
  12. type: Object,
  13. default: () => ({}),
  14. },
  15. })
  16. defineOptions({
  17. name: 'HcCharts',
  18. })
  19. //初始变量
  20. let chart = null
  21. const echart = ref(null)
  22. const options = ref(getObjValue(props.option))
  23. //深度监听
  24. watch(() => [
  25. props.option,
  26. ], ([option]) => {
  27. options.value = getObjValue(option)
  28. setOptions(options.value)
  29. }, { deep: true })
  30. //初始化图表
  31. const initChart = () => {
  32. chart = echarts.init(echart.value)
  33. setOptions(options.value)
  34. }
  35. //监听浏览器窗口变化
  36. const windowResize = () => {
  37. window.addEventListener('resize', resizeEvent)
  38. }
  39. const resizeEvent = () => {
  40. window.requestAnimationFrame(() => {
  41. chart.resize()
  42. })
  43. }
  44. //设置图表
  45. const setOptions = (option) => {
  46. nextTick(() => {
  47. chart.setOption(option)
  48. })
  49. }
  50. //渲染完成
  51. onMounted(() => {
  52. nextTick(() => {
  53. initChart()
  54. windowResize()
  55. })
  56. })
  57. //被卸载
  58. onUnmounted(() => {
  59. window.removeEventListener('resize', resizeEvent)
  60. chart.dispose()
  61. chart = null
  62. })
  63. const onResize = () => {
  64. nextTick(() => {
  65. chart.resize()
  66. })
  67. }
  68. // 暴露出去
  69. defineExpose({
  70. onResize,
  71. })
  72. </script>
  73. <style lang="scss" scoped>
  74. .hc-echarts-box {
  75. display: block;
  76. height: 100%;
  77. overflow: hidden;
  78. position: relative;
  79. .hc-echarts {
  80. position: absolute;
  81. bottom: 0;
  82. left: 0;
  83. right: 0;
  84. z-index: 2;
  85. width: 100%;
  86. height: 100%;
  87. }
  88. }
  89. </style>