index.vue 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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.setOption(option)
  45. })
  46. }
  47. //渲染完成
  48. onMounted(() => {
  49. nextTick(() => {
  50. initChart()
  51. windowResize()
  52. })
  53. })
  54. //被卸载
  55. onUnmounted(() => {
  56. window.removeEventListener("resize",resizeEvent);
  57. chart.dispose()
  58. chart = null
  59. })
  60. const onResize = () => {
  61. nextTick(() => {
  62. chart.resize();
  63. })
  64. }
  65. // 暴露出去
  66. defineExpose({
  67. onResize
  68. })
  69. </script>
  70. <style lang="scss" scoped>
  71. .hac-echarts-box {
  72. display: block;
  73. height: 100%;
  74. overflow: hidden;
  75. position: relative;
  76. .hac-echarts {
  77. position: absolute;
  78. bottom: 0;
  79. left: 0;
  80. right: 0;
  81. z-index: 2;
  82. width: 100%;
  83. height: 100%;
  84. }
  85. }
  86. </style>