VUE 3.0下使用echarts5.1.1,点击legend报错Cannot read property 'type' of undefined
让我们先来看看报错
bug复现
- 点击lenged选择不同的数据条目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/484874bc041b8fbbc165c97c3419e82f.png)
- 报错
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6fb38225a6726da11678b50bef5df1fc.png)
3.报错详情
seriesModel.coordinateSystem为undefined
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f804948de43375f40a9e6eba9b2215bc.png)
bug解决思路
- 首先保持vue版本不变,我将echarts降级为4.7.0版本,同样会有这个报错
- 保持ehcarts版本不变,我将vue降级为2.7.1版本,发现这个报错竟然消失了!!
- 那么可以得出,我的getOption()和setOption()的代码层面是无误的
- 接下来就是去找mounted过程中产生错误的原因
解决
- 先看旧代码
这里在data里定义了myEcharts=null,以至于echarts.init在初始化时是可行的,但是在切换series或者resize时时会报错的
setup(props) {
const dataMap = reactive({
showEmpty: false,
myEcharts:null,
});
onMounted(() => {
const echarts = inject('ec');
nextTick(() => {
dataMap.myEcharts = echarts.init(document.getElementById(props.echartId));
window.addEventListener('resize', function () {
dataMap.myEcharts.resize();
});
dataMap.myEcharts.clear();
props.option && dataMap.myEcharts.setOption(props.option, true);
});
});
return {
dataMap,
};
},
- 新代码
在onMounted内部定义const myEcharts = echarts.init!!,由于我的id是父组件通过props值传递传给echarts组件的,所以我加上了nextTick方法在下次 DOM 更新循环结束之后执行延迟回调,这样绘制的图表就没有问题了
setup(props) {
const dataMap = reactive({
showEmpty: false,
});
onMounted(() => {
const echarts = inject('ec');
nextTick(() => {
const myEcharts = echarts.init(document.getElementById(props.echartId));
window.addEventListener('resize', function () {
myEcharts.resize();
});
myEcharts.clear();
props.option && myEcharts.setOption(props.option, true);
});
});
return {
dataMap,
};
},
附上完整代码
<template>
<div class="echarts">
<div class="echarts" :id="echartId"></div>
</div>
</template>
<script>
import { defineComponent, onMounted, reactive, inject, nextTick, watch } from 'vue';
export const echartLoadingOptions = { color: '#1890ff', fontSize: 14 };
export default defineComponent({
name: 'echart',
props: {
option: {
type: Object,
default() {
return {};
},
},
echartId: {
type: String,
default: function () {
return '';
},
},
},
setup(props) {
const echarts = inject('ec');
const dataMap = reactive({
showEmpty: false,
});
onMounted(() => {
nextTick(() => {
const myEcharts = echarts.init(document.getElementById(props.echartId));
window.addEventListener('resize', function () {
myEcharts.resize();
});
myEcharts.clear();
props.option && myEcharts.setOption(props.option, true);
watch(
() => props.option,
() => {
myEcharts.clear();
props.option && myEcharts.setOption(props.option, true);
}
);
});
});
return {
dataMap,
};
},
});
</script>
<style scoped>
.echarts {
width: 100%;
height: 100%;
}
</style>