最近使用element-ui做的后台管理要求嵌入图表功能,其实element-ui嵌入图表很简单,但是问题来了.
开发场景是:页面上有多个图表,当我调整浏览器窗口大小的时候,发现图表并不会根据浏览器窗口大小而进行调整,这完全不符合我们的要求,也是作为一个合格的开发人员不能容忍的.
我的页面内有两个echarts图表,下面是我的解决方案:(vue 代码)

//data 里面定义的两个图表
data: function () {
	return {
			myChart1:"",
			myChart2:"", 
		}
	},
//mounted 里面的代码,需要注意的是当浏览器窗口大小变化时候,页面不会执行_this.initEchart();这句代码,而只会执行window.onresize里面的代码 
mounted(){
	let _this=this;
	_this.initEchart();
	window.onresize =()  =>{
           return (()=>{
            _this.myChart1.resize();
            _this.myChart2.resize(); 
        })()
           }
},
//methods 里面的方法
//setOption里面是我的图表配置的参数,你们可要可不要
initEchart(){
	this.myChart1=this.echarts.init(document.getElementById("echart1"));
	this.myChart1.setOption({
		title : {
			text: '某地区蒸发量和降水量',
			textStyle:{
				fontSize:"20",
				fontWeight:"bold",
			}
		},
		tooltip : {
			trigger: 'axis'
		},
		legend: {
			orient : 'horizental',
			x : 'right',
			data:['降水量']
		},
		xAxis : [
			{
				type : 'category',
				data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
			}
		],
		yAxis : [
			{
				type : 'value'
			}
		],
		series : [
			{
				name:'降水量',
				type:'bar',
				barWidth:"10",
				itemStyle: {
					normal: {
						color: "rgb(53,146,108)",
					}
				},
				data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
			}
		]
	});
	this.myChart2=this.echarts.init(document.getElementById("echart2"));
	this.myChart2.setOption({
		title : {
			text: '未来一周气温变化',
			textStyle:{
				fontSize:"20",
				fontWeight:"bold",
			}
		},
		tooltip : {
			trigger: 'axis'
		},
		legend: {
			orient : 'horizental',
			x : 'right',
			data:['最高气温']
		},
		calculable : true,
		xAxis : [
			{
				type : 'category',
				boundaryGap : false,
				data : ['周一','周二','周三','周四','周五','周六','周日']
			}
		],
		yAxis : [
			{
				type : 'value',
				axisLabel : {
					formatter: '{value} °C'
				}
			}
		],
		series : [
			{
				name:'最高气温',
				type:'line',
				itemStyle: {
					normal: {
						color: "rgb(53,146,108)",
					}
				},
				data:[14, 11, 15, 13, 12, 13, 8],
			}
		]
	}); 
	},

图表根据浏览器窗口大小变化的问题已经解决了,那么下面我给大家附上我是如何在element-UI里面使用echarts图表的.

  1. 安装echart依赖

npm install echarts --save

  1. 在main.js写入如下代码,写入之后就可以全局引用了

import echarts from ‘echarts’
Vue.prototype.echarts=echarts;
Vue.use(echarts);

  1. 在需要使用图表的页面里直接使用即可
//html
  <div id="echart1"  ></div>
//script
 data: function () {
	return {
		myChart1:"", 
		option:{},//图表配置
	}
},
mounted(){ 
	this.initEchart();
},
methods: {
	initEchart(){
		this.myChart1=this.echarts.init(document.getElementById("echart1"));
		this.myChart1.setOption( this.option);	
		}
}

为大家附上Echart官网文档地址:添加链接描述

以上内容仅供大家参考,如果有疑问,欢迎大家留言,希望大家互相交流学习

Logo

前往低代码交流专区

更多推荐