问题缘起
后台的一个AntV G2图表在侧边菜单栏收缩或展开后并没有“自适应”新的宽高——虽然设置了autoFit: true
。
解决1
首先想到的自然而然是针对侧边菜单折叠事件添加一个订阅,并在订阅回调中强制重绘图表。如下:
typescriptCopy code- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
this.siderListener = this.commonService.siderCollapsed$.subscribe((collapsed) => {
if (this.postChart) {
console.log(1, this.postChart.viewBBox.width, this.postChart.viewBBox.height);
const chartEle = document.getElementById('countChart');
console.log(2, chartEle?.clientWidth, chartEle?.offsetWidth, chartEle?.scrollWidth);
setTimeout(() => this.postChart.forceFit(), 200);
}
});
this.siderListener = this.commonService.siderCollapsed$.subscribe((collapsed) => {
if (this.postChart) {
console.log(1, this.postChart.viewBBox.width, this.postChart.viewBBox.height);
const chartEle = document.getElementById('countChart');
console.log(2, chartEle?.clientWidth, chartEle?.offsetWidth, chartEle?.scrollWidth);
setTimeout(() => this.postChart.forceFit(), 200);
}
});
然而,输出的结果却是记录的上一次宽高,即便加上了setTimeout
(但定时器间隔设久一些,比如>200ms,可以取到更新后的宽高)。