1.现象
"echarts": "^5.4.0",
"vue": "^3.2.25",
调用 echarts.resize()不生效并且报错
2.原因分析
-
由于之前vue2中会在data中定义echarts实例,并且通过 this.echarts.xxx() 来调用API并未出现异常 所以在vue3惯性使用ref定义实例
-
重新查看echarts官网,vue3中 echarts 的实例不应该是响应式的 因为它可能会影响对内部模型属性的访问,并带来一些意想不到的问题
- [Bug] tooltip.trigger 为折线图中的轴时,tooltip 不显示,tooltip.trigger 为 item 时没问题 #17496
- [Bug] 单击按钮更改直方图的设置选项时,不再显示直方图的工具提示 #16681
- [Bug] 热图视觉图过滤不起作用 - CoordSys 未定义 #16659
- [Bug] ECharts.resize() 错误!无法读取未定义的属性(读取“类型”) #16642
- vue3.x & echartsV5.2.1,当我点击图表上的 [ legend ] 时,Console error: coordSys is undefined #16061
- vue3 使用 ref 变量获取 ID 节点触发:axis则无法显示框,item不会提示影响 #15845
- vue3中的treemap异常 #15967
- vue3.vue3.折线图提示图0显示工具提示.trigger轴',且不显示工具提示的格式化程序 #15457
- vue3使用echarts5,折线图、柱状图使用datazoom报错 #14974
- Vue3项目中使用折线图出现tooltip不显示 #14342
- vue3 项目示例报错后示例点击点击图无法正常使用 #14339
- 调整大小错误 #15253
- vue3.0下echarts resize()报错 #13943
- vue3 图表无法再次渲染 #13537
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>