在vue中使用echarts

功能介绍:

在vue开发中,希望实现eharts图表展示,节省init初始化、resize自适应代码。

具体实现:

一、安装echarts依赖:
npm install echarts -S
或者使用淘宝的镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install echarts -S
二、全局引入:

全局引用这里遇到些问题,安装好echarts后,使用第一种引用方式时,控制台报错并且echarts图表无法显示。
在这里插入图片描述
搜索后发现是安装的echarts版本比较新,修改main.js文件中的引用解决问题。

// 引入echarts
import echarts from 'echarts';
// 当版本达到5.1.2时,使用下面这种引用方式
import * as echarts from 'echarts';

Vue.prototype.$echarts = echarts;
三、自定义组件:

新建c-echarts.vue文件放在components文件夹下:

<!-- div标签id、样式设为动态 -->
<template>
  <div>
    <div :id="options.ele" :style="{width: '100%', height: '300px'}"></div>
  </div>
</template>
export default {
	props: {
    	options: {}
  	},
  	data () {
	    return {
	      chartsName: null
	    };
  	},
  	watch: {
	    options: {
			deep: true,
			handler(newVal) {
		    	this.setCharts(newVal);
		    }
	    }
	},
	methods: {
		setCharts (options) {
    		if (options) {
        		this.chartsName = this.$echarts.init(document.getElementById(options.ele));
        		// 绘制图表
        		this.chartsName.setOption(options.setOpt);
      		}
    	}
	}
}
四、增加宽高自适应:
beforeDestroy () {
	// 移除监听
	window.removeEventListener('resize', this.resizeCharts, false);
},
mounted() {
	this.setCharts(this.options);
	// 监听resize方法
	window.addEventListener('resize', this.resizeCharts, false);
},
methods: {
	resizeCharts () {
    	this.chartsName.resize();
    }
}
五、全局引用:

修改main.js文件

// 自定义echarts
import vEcharts from 'components/common/c-echarts';

// 全局注册自定义echarts组件
Vue.component('v-echarts', vEcharts);
六、使用:
<v-echarts :options="lineCharts" ref="echarts"></v-echarts>
data() {
    return {
    	lineCharts: {
    		ele: 'lineCharts',
    		setOpt: {
    			// 存放echarts里面横纵坐标、图例等配置项
    			legend: {},
    			xAxis: {
        			type: 'category',
        			data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
   				},
			    yAxis: {
			        type: 'value'
			    },
			    series: [{
			        data: [150, 230, 224, 218, 135, 147, 260],
			        type: 'line'
			    }]
			}
    	}
	};
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值