一、處理echarts因v-if切換後圖形顯示異常
有時候我們需要在一個頁面中使用v-if來顯示不同的兩個圖表。
視覺效果上好像是從一個頁面點擊鏈接跳轉到另一個頁面,但其實原理是通過銷燬和重建兩個不同dom容器來實現這個效果。
可能會出現的問題:
在切換到另一個圖表顯示的時候,改變了窗口寬度高度,那麼點擊返回按鈕時看到原先的echarts圖形就會有一部分消失顯示不完整了。
解決辦法:
我們需要在返回這個按鈕上加個定時器延遲,來主動觸發窗口發生變化(前提是代碼也有做監聽窗口變化改變圖形大小的操作,下面標題二會講解)。這樣圖形能正確自動渲染變化一次。
methods: {
// 關閉監控ip執行詳情頁
closePerfExe () {
this.isShowPerfExe = false // 控制當前dom容器的顯示
// 當在監控ip詳情頁點擊回性能分析頁的時候,加個延遲主動觸發窗口變化,這樣窗口改變性能分析頁就不會發生圖表顯示不完整的情況了
// 這裏的代碼是關鍵!!!
setTimeout( () => {
let triggerResize = new Event('resize')
window.dispatchEvent(triggerResize)
},0)
}
}
二、vue實現echarts監聽窗口變化而改變大小
監聽窗口的變化,echarts圖形大小跟着變化。
注意:在組件銷燬時記得也要移除監聽。
data () {
return {
myChartPerformance: '', // echarts的dom容器
performanceOption: '' // echarts配置項option
}
},
mounted () {
// 一般我爲了防止出現一些切換問題,都是先清除echarts再初始化
if(this.myChartPerformance){
this.myChartPerformance.clear()
}
this.myChartPerformance = echarts.init(document.getElementById('myChartPerformance'))
// 圖表數據配置
this.performanceOption = {
title: {
text: chartOptions.titleName
},
tooltip: {
trigger: 'axis'
},
//.........
//.........
}
// 設置圖表數據配置
this.myChartPerformance.setOption(this.performanceOption)
// 監聽窗口大小改變圖表大小(先移除再監聽,防止出錯)
window.removeEventListener('resize', this.resizePerformanceFun)
window.addEventListener('resize', this.resizePerformanceFun)
},
beforeDestroy () {
// 組件銷燬前移除監聽
window.removeEventListener('resize', this.resizePerformanceFun)
},
methods : {
resizePerformanceFun () {
if(this.myChartPerformance){
// console.log('窗口改變了,重新渲染圖形')
this.myChartPerformance.resize()
}
}
}