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)
}
})
}
})
