vue3中使用Echarts图表报错 Uncaught TypeError: Cannot read properties of undefined (reading ‘type‘)
·

解决:
初始化图表时使用 markRaw() 包裹下
<template>
<div class="chart-box" ref="chartRef"></div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, markRaw } from 'vue';
import * as echarts from 'echarts';
import 'echarts-gl';
const chartRef = ref(null);
const chartInstance = ref(null);
const getOption = () => {
const option = { ... };
return option;
};
// 窗口resize处理
const resizeHandler = () => {
if (chartInstance.value) {
chartInstance.value.resize();
}
};
// 销毁图表实例
const handleDestroy = () => {
if (chartInstance.value) {
chartInstance.value.dispose();
chartInstance.value = null;
}
window.removeEventListener('resize', resizeHandler);
};
onMounted(async () => {
const chartDom = chartRef.value;
if (!chartDom) return;
if (chartInstance.value) {
chartInstance.value.dispose();
}
await nextTick();
chartInstance.value = markRaw(echarts.init(chartRef.value));
const option = getOption();
chartInstance.value.setOption(option)
window.addEventListener('resize', resizeHandler);
})
onBeforeUnmount(() => {
handleDestroy();
});
</script>
<style lang="scss" scoped>
.con-child {
width: 100%;
height: 300px;
}
</style>
markRaw():标记一个对象,使其永远不会被 Vue 的响应式系统转换(即不会变成 reactive 或 ref)。被标记的对象会成为一个 “原始对象”,即使后续尝试用 reactive()、ref() 等方法包裹它,也不会生效。
使用场景:
- 处理第三方库实例:比如 ECharts 实例、地图 SDK 实例、视频播放器实例(像你代码里的
JessibucaPlayer对应的播放器实例),这类实例不需要响应式,标记为 raw 可避免 Vue 对其代理导致的性能问题或异常。 - 不可变的静态数据:比如固定的配置项、枚举值,不需要响应式更新,标记后能提升性能。
- 避免响应式嵌套循环:如果对象内部包含自身引用,响应式转换可能导致死循环,markRaw 可规避这个问题。
更多推荐
所有评论(0)