大屏搭建多个图表不自适应问题
场景:
使用 Vue3+ECharts 搭建数字大屏时,我的思路是在一个Vue父组件中使用Grid布局,来搭建整个页面,使用多个Vue组件去做每个图表的容器,效果如下:
父组件代码如下:
<template><div v-if="isLogin" class="dashboard-grid"><left-top-module class="item-left-top" /><right-top-module class="item-right-top" /><left-module class="item-left" /><right-module class="item-right" /><middle-module class="item-middle" /><left-bottom-module class="item-left-bottom" /><middle-left-module class="item-middle-left" /><middle-right-module class="item-middle-right" /><right-bottom-module class="item-right-bottom" /></div>
</template><script setup>
import { ref, onMounted } from 'vue'
import { getSSOToken } from "@/request/admin.js";
import { ssoLogin } from "@/util/auth.js";
import LeftTopModule from './components/leftTopModule.vue'
import RightTopModule from './components/rightTopModule.vue'
import LeftModule from './components/leftModule.vue'
import RightModule from './components/rightModule.vue'
import MiddleModule from './components/middleModule.vue'
import LeftBottomModule from './components/leftBottomModule.vue'
import MiddleLeftModule from './components/middleLeftModule.vue'
import MiddleRightModule from './components/middleRightModule.vue'
import RightBottomModule from './components/rightBottomModule.vue'const isLogin = ref(false)const visitLoginStatus = () => {const formData = {grant_type: "refresh_token"}getSSOToken(formData).then(res => {isLogin.value = truewindow.sessionStorage.setItem('access-token', res.data.access_token)}).catch(err => {console.log(err)if(err.response.status === 401) {console.log('Not logged in!')isLogin.value = falsessoLogin()}})
}onMounted(() => {visitLoginStatus()
})
</script><style scoped>
.dashboard-grid {display: grid;gap: 0;width: 100%;height: 100vh;margin: 0;padding: 0;overflow-x: hidden;grid-template-columns: repeat(4, 1fr);grid-template-rows: 1fr 1fr 1fr;grid-template-areas:"lt middle middle rt""l middle middle r""lb ml mr rb";
}.dashboard-grid > * {min-width: 0;min-height: 0;
}.item-left-top { grid-area: lt; }
.item-right-top { grid-area: rt; }
.item-left { grid-area: l; }
.item-right { grid-area: r; }
.item-middle { grid-area: middle; }
.item-left-bottom { grid-area: lb; }
.item-middle-left { grid-area: ml; }
.item-middle-right { grid-area: mr; }
.item-right-bottom { grid-area: rb; }
</style>
问题及解决方案:
每个子组件中我都使用了一个ECharts图表组件:
<div ref="chartRef" class="chart-content"></div>
在我改变分辨率尺寸的时候:
- 只有一个图表组件:自适应正常
- 多个图表组件:都不自适应,或者只有一个图表组件自适应,并且只有当分辨率变大的时候可以跟着自适应,分辨率变小的时候不会自适应
并且使用了 .resize() 方法也还是无法实现自适应
单图表组件
首先是只使用一个图表组件时, 可以编写如下代码实现自适应:
<template><div class="module placeholder"><div ref="chartRef" class="chart-content"></div></div>
</template><script setup>
import * as echarts from "echarts"
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue"const chartRef = ref(null)
let chartInstance = null
let resizeObserver = nullconst getCharts = () => {chartInstance.setOption(...图表配置省略...)
}const handleResize = () => {chartInstance?.resize()
}onMounted(async () => {await nextTick()if (!chartRef.value) returnchartInstance = echarts.init(chartRef.value)getCharts()window.addEventListener('resize', handleResize)resizeObserver = new ResizeObserver(handleResize)resizeObserver.observe(chartRef.value)
})onBeforeUnmount(() => {window.removeEventListener('resize', handleResize)if (resizeObserver) {resizeObserver.disconnect()resizeObserver = null}if (chartInstance) {chartInstance.dispose()chartInstance = null}
})
</script><style scoped>
.module.placeholder {height: 100%;width: 100%;display: flex;flex-direction: column;box-sizing: border-box;
}.chart-content {flex: 1;width: 100%;height: 100%;
}
</style>
多图表组件
将监听方法进行封装,创建 resize.js:
import { onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'export function useEcharts(chartRef, renderChart) {let chartInstance = nulllet resizeObserver = nullconst handleWindowResize = () => {chartInstance?.resize()}const init = () => {if (!chartRef.value) returnchartInstance = echarts.init(chartRef.value)renderChart(chartInstance)}onMounted(async () => {await nextTick()init()window.addEventListener('resize', handleWindowResize)resizeObserver = new ResizeObserver(handleWindowResize)resizeObserver.observe(chartRef.value)})onBeforeUnmount(() => {if (resizeObserver && chartRef.value) {resizeObserver.unobserve(chartRef.value)resizeObserver.disconnect()}window.removeEventListener('resize', handleWindowResize)if (chartInstance) {chartInstance.dispose()chartInstance = null}})
}
在各个子组件中这样使用即可:
<template><div class="module placeholder"><div ref="chartRef" class="chart-content"></div></div>
</template><script setup>
import * as echarts from "echarts"
import { ref } from "vue"const chartRef = ref(null)const getCharts = (instance) => {instance.setOption(...图表配置省略...)
}useEcharts(chartRef, getCharts)
</script><style scoped>
.module.placeholder {height: 100%;width: 100%;display: flex;flex-direction: column;box-sizing: border-box;
}.chart-content {flex: 1;width: 100%;height: 100%;
}
</style>
一开始,我封装了公共方法之后,还是无法实现自适应,经过漫长的排查之后,最终发现是由于父组件需要设置:
.dashboard-grid {/* ...其他省略,上面有,下面是核心 */width: 100%;overflow-x: hidden;
}.dashboard-grid > * {min-width: 0;min-height: 0;
}
并且子组件必须保证没有设置最小宽度和最小高度:
.module.placeholder,
.chart-content {min-width: 0;min-height: 0;overflow: hidden;
}
这样之后是可以成功实现多个图表组件的自适应的,原因主要是:
单图表:占用整个第一列,Grid track 宽度本身就由剩余空间撑满,canvas 或许没有“超出”它的最小内容宽度,所以收缩表现正常。
多图表:多个 canvas 各自在不同行,如果都建立了内在最小宽度,又被 Grid track 的 1fr 算法平分,就会出现“只能拉大不能拉小”的假象。
.dashboard-grid > * { min-width: 0; } 这句最关键,清掉了 Grid 子项的最小宽度限制,保证它们在窗口缩小时能真正变窄。