ps:实例使用技术为vue3+ts
1. echarts设置了width: 100%但是显示的只有100px,原因是:切换tab之前tab的样式为display: none所以echarts的父元素宽度为0
2. 故而想到在切换tab的时候设置点击事件,并在获取到tab的宽度之后重新渲染echart
<!--注意设置chart外层,此处即为el-tabs和el-tab-pane的宽高--> <el-tabs v-model="activeTab" @tab-click="handleTabClick"> <el-tab-pane name="1" label="tab1"> <div ref="chartRef" :style="{width: '100%', height: '200px'}" ></div> </el-tab-pane> </el-tabs>
复制
//注意要全局注册echarts import {getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref} from 'vue' import type { ECharts } from "echarts"; const { proxy } = getCurrentInstance() as any const echarts = proxy.$echarts; const chartRef = ref(null) let echart: ECharts const echartOption = reactive({ data: {/* 此处为echarts的option数据 */} }) onMounted(() => { initOption() window.addEventListener('resize', resizeHandler) }); const resizeHandler = () => { if (echart) { echart.resize() } } //卸载页面,销毁window.onresize事件 onBeforeUnmount(() => { window.onresize = null }) const initOption = () => { echart = echarts.init(chartRef.value) echart.setOption(echartOption.data) } const handleTabClick = (tab: any) => { if (tab.props.name === '1') { let time = setTimeout(() => { resizeHandler() clearTimeout(time) }, 200) } }
复制