vue+echarts中 图表容器无法自适应父级div

项目场景:

vue+echarts中 图表容器无法自适应


问题描述:

在做项目时,遇到问题,百度了很多都无法实现,解决之后总结一下,方便下次参考。

设置图表宽度为百分比,不生效,无法随着外层父容器大小自适应
补充:项目页面中加入左侧折叠菜单,点击折叠后,父容器百分比自适应浏览器,但是图表大小无法自适应父容器的调整。


原因分析:

调试发现 width:100%,变成了width:100px。并没有按照百分比实现自适应。


解决方案:

利用resize()方法来解决该问题。

leftMenu.vue折叠按钮事件添加发射事件resize

method:{
clickButton:function(){
....
//新的界面要添加该事件,最好更名事件名(resize1...)
添加到延时事件
setTimeout(this.$root.eventHub.$emit('resize'),200);
}

main.vue

<template>
	<div style="width:60%;height:30%;">
	//此处我只改变图表宽度自适应,高度固定
		<div id="demoChart" style="width:100%;height:300px;"></div>
	</div>
</template>
<script>
	export default{
		name:"ChartShow",
		data(){
			return{
			myChart:null
			}
		},
		mounted(){
		//基于准备好的DOM,初始化echarts实例
		this.myChart = this.$echarts,init(document.getElementById('demoChart')
		//注意顺序,画图写在初始化实例之后
		this.drawPie()
		this.$root.eventHub.$on('resize', () => {
                 setTimeout(this.resizeChart,10);
            })
		},
		method:{
			drawPie(){
			//绘制图表
			this.myChart.setOption({
				legend:{
					type:'scroll',//图例过长,滚动显示
					top:'top',
					data:['苹果','香蕉','橘子','火龙果','荔枝']
				},
				tooltip:{
					trigger:'item',
				},
				series: [{
                        name: '最受欢迎的水果',
                        type: 'pie',
                        radius: [50, 95],
                        center: ['50%', '55%'],
                        avoidLabelOverlap:false,
                        label:{
                            show:false,
                            position:'center',
                        },
                        emphasis:{
                            label:{
                                show:true,
                                fontSize:'20',
                                fontWeight:'bold',
                            }
                        },
                        labelLine: {
                           show:false,
                        },
                        data: [
                            {value: 25, name: '苹果'},
                            {value: 32, name: '香蕉'},
                            {value: 12, name: '橘子'},
                            {value: 55, name: '海事'},
                            {value: 85, name: '火龙果'},
                            {value: 45, name: '荔枝'},
                        ]
                    }]
			})
			}
		}
		resizeChart(){
		this.myChart.resize();
	}
</script>

如果想要高度自适应,同理调整。


版权声明:本文为weixin_47026347原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。