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'
}]
}
}
};
}