使用echart最让人头疼的就是尺寸大小的设置,经常性的出现不符合预期的效果。
问题1:当把width设置是有tab时,切换显示的尺寸一直是100px;
解决办法:放弃事业tab,换成el-radio组件,效果不错。
问题2:没有使用element的tab组件,仍然出现了该现象。
解决办法:把生成echart的元素包装成一个单独的子组件,在使用的地方引入包装后的该组件,然后在调用地方的外层组件中,使用v-if进行控制。这样就可以完美显示正常尺寸。
网上也看了很多解决方法,实验了很多不生效。最终使用上面的2个办法解决了目前我遇到的问题,希望对你有帮助。
下面是我在项目中封装的MyChart.vue组件。
<template>
<div class="line-chart">
<div ref="lineChart" :style="{ width: width, height: height }"></div>
</div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, GraphicComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
GridComponent,
TooltipComponent,
GraphicComponent,
LineChart,
CanvasRenderer,
UniversalTransition,
]);
let myChart: any = null;
const lineChart = ref();
const props = defineProps({
width: {
type: String,
default: '100%',
},
height: {
type: String,
default: '100%',
},
chartOption: {
type: Object,
default: () => {
return {
xAxis: {
type: 'category',
data: [],
},
yAxis: {
type: 'value',
},
tooltip: {
trigger: 'axis',
},
grid: {
x: 35,
y: 15,
x2: 5,
y2: 5,
borderWidth: 1,
},
series: [],
};
},
},
});
watch(
() => props.chartOption,
(propData) => {
nextTick(() => {
chartResize();
myChart?.setOption(propData, true);
});
},
{ deep: true, immediate: true }
);
onMounted(() => {
myChart = echarts.init(lineChart.value);
myChart?.setOption(props.lineData, true);
window.addEventListener('resize', chartResize);
});
onUnmounted(() => {
myChart?.dispose();
window.removeEventListener('resize', chartResize);
});
const chartResize = () => {
myChart?.resize();
};
</script>
<style lang="scss" scoped>
#lineChart {
width: 100%;
height: 300px;
}
</style>
在使用的地方进行引入调用即可
<MyChart
:lineOption="lineOption"
v-if="chartData.length>0"
height="200px"
/>