vue3 echarts 横竖屏切换后更新尺寸
时间: 2023-05-10 15:01:28 浏览: 71
在Vue3中,如果想在echarts图表横竖屏切换后更新尺寸,需要在组件挂载或更新完成后进行尺寸调整,并且要判断横竖屏状态进行相应的调整。
具体实现方式可以采取以下步骤:
1.在组件挂载或更新完成后,获取echarts实例和容器节点:
mounted() {
this.chart = echarts.init(this.$refs.chart);
this.container = this.$el;
this.resizeChart();
},
updated() {
this.resizeChart();
}
2.定义resizeChart函数,通过调整echarts实例和容器节点的宽高,实现尺寸的更新:
resizeChart() {
const orientation = window.orientation || 0;//获取设备方向(竖屏0/横屏90/横屏-90)
const width = orientation === 0 ? this.$el.offsetWidth : this.$el.offsetHeight;//根据方向获取容器宽高,用于设置echarts尺寸
const height = orientation === 0 ? this.$el.offsetHeight : this.$el.offsetWidth;
this.chart.resize({ width, height });
}
3.监听窗口的orientationchange事件,根据设备方向变化触发resizeChart函数更新尺寸:
created() {
window.addEventListener("orientationchange", this.resizeChart);
},
beforeDestroy() {
window.removeEventListener("orientationchange", this.resizeChart);
}
通过以上步骤,即可在Vue3中实现echarts图表横竖屏切换后的尺寸更新。