index.vue 1.8 KB

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