使用 ResizeObserver 解决 echarts 跟随父容器大小变化问题

282 阅读1分钟

vue项目使用ResizeObserver 解决 echarts 跟随父容器大小变化问题

<template>
  <div ref="chartRef" style="width: 100%; height: 100%;" />
</template>

<script setup>
import { ref, toRefs, shallowRef, watch, onMounted, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts/core'

const props = withDefaults(
  defineProps<{
    options: Object
    theme?: string
  }>(),
  {
    theme: 'light'
  }
)

const { theme, options } = toRefs(props)

const chartRef = ref(null)
const chartExample = shallowRef(null)

watch(
  options,
  (val) => {
    val && chartExample.value && chartExample.value.setOption(val, true)
  },
  { deep: true }
)

// 用于创建ResizeObserver对象
let observer = null

onMounted(() => {
  nextTick(() => {
    const { offsetWidth, offsetHeight } = chartRef.value
    if (offsetHeight && offsetWidth) {
      chartExample.value = echarts.init(chartRef.value, theme.value)
      options && chartExample.value.setOption(options.value, true)

      // 创建ResizeObserver对象。并且把echartsInstance.resize作为监听后回调函数传入
      observer = new ResizeObserver(chartExample.value.resize)
      observeRectChange()
    }
  })
})

onUnmounted(() => {
  disconnectRectChange()
})

// 对echart进行监听
const observeRectChange = () => {
  observer?.observe(chartRef.value as HTMLElement)
}
// 取消和结束目标对象上所有对echart的观察。
const disconnectRectChange = () => {
  observer?.disconnect()
}
</script>