1、情况说明
1)有多个Echarts 图表,且每个作图的内容 是单独的组件
2)使用 v-show 指令切换显示 图表,每次只显示一个
index 就是索引号,每次切换
<data-chart key="0" v-show="index=== 0" :index="index" :type='0' />
<data-chart key="1" v-show="index=== 1" :index="index" :type='1' />
<data-chart key="2" v-show="index=== 2" :index="index" :type='2' />
1)每次切换后图表会变窄,这是因为 在各个chart display none 和 block 切换后,获取不到容器的实际高宽,图表的宽度会将 100% 转换为 100px,所以 需要手动调用 resize 方法获取正确的高宽并且刷新画布。
2)使用watch 检测index 变化 ,直接调用 chartInstance.resize()
3)结果画布大小没有改变,还是窄的
原因: 因为index变化后,容器切换成block,这个变化组件很快就检测到了,但DOM渲染还没有完成,所以立即调用 resize(), 获取的还是之前display: none的宽高,所以需要等待一定的时间
也就是说 需要在 DOM 准备好后,resize()才能正确执行
监视 index 变化,调用resize()
2 组件代码示意
export default defineComponent({
props: {
type: {
type: Number,
default: 0, //
required: true
},
index: {
type: Number,
default: 0, // 当前显示的数据
required: true
},
},
setup(props: any) {
const _props = toRefs(props)
watch(_props.index, () => {
if (_props.index == _props.type) {
setTimeout(() => {
if (chartInstance) chartInstance.resize()
}, 10)
}
})
}
})