vue3中使用echarts使用resize()报错

2,124 阅读1分钟

1.现象

 "echarts": "^5.4.0",
 "vue": "^3.2.25",
 调用 echarts.resize()不生效并且报错

image.png

2.原因分析

  • 由于之前vue2中会在data中定义echarts实例,并且通过 this.echarts.xxx() 来调用API并未出现异常 所以在vue3惯性使用ref定义实例

  • 重新查看echarts官网,vue3中 echarts 的实例不应该是响应式的 因为它可能会影响对内部模型属性的访问,并带来一些意想不到的问题

3.解决

下面是封装的echarts组件
<script lang="ts" setup>
   //按需引入
  import echarts from '@/utils/echarts/index';
  //引入实例类型
  import { EChartsType } from 'echarts/core';
  //引入echarts的默认配置
  import { ECHARTS } from '@/const';
  //引入配置的类型
  import { ECOption } from '@/utils/echarts/index';
  //防抖函数
  import { debounce } from '@/utils/function/index';

  const props = defineProps({
    optionParam: {
      type: Object,
    },
  });

  const echartsRef = shallowRef<HTMLDivElement>();
  /*let lineEcharts = ref<EChartsType>();
    let lineEcharts: EChartsType | null = null;
    将ref改为shallowRef或者直接声明
   */
  let lineEcharts = shallowRef<EChartsType>();
  
  const echartsOption = reactive<ECOption>(ECHARTS.OPTION.BASE_LINE);

  const handlerResize = debounce(() => {
    lineEcharts.value?.resize();
  }, 200);
  watch(props, () => {
    lineEcharts.value?.setOption(props.optionParam ?? { notMerge: true });
  });

  onMounted(() => {
    initEcharts();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', handlerResize);
  });

  const initEcharts = () => {
    lineEcharts.value = echarts.init(echartsRef.value as HTMLDivElement);
    lineEcharts.value.setOption(echartsOption);

    lineEcharts.value.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: true,
    });
    window.addEventListener('resize', handlerResize);
  };
</script>
<template>
  <div class="echarts" ref="echartsRef"></div>
</template>

<style lang="scss" scoped></style>