有时候我们需要在一个页面中使用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()
}
}
}
一、处理echarts因v-if切换后图形显示异常
最新推荐文章于 2023-11-21 09:50:30 发布