介绍:
ECharts 是一个使用 JavaScript 实现的开源可视化库,涵盖各行业图表,满足各种需求。
ECharts 遵循 Apache-2.0 开源协议,免费商用。
ECharts 兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Safari等)及兼容多种设备,可随时随地任性展示。
第一步:先在main.js引入所需的组件,如下图
import ECharts from 'vue-echarts';
import 'echarts/lib/chart/line'; //折线图
import 'echarts/lib/chart/pie'; //饼形图
import 'echarts/lib/chart/bar'; //柱状图
import 'echarts/lib/component/legend'; //描述
import 'echarts/lib/component/tooltip'; //鼠标提示
import 'echarts/lib/component/title'; //图标题
import 'echarts/lib/component/grid';
Vue.component('v-chart', ECharts);
第二步:根据项目的组件加载方式,编写相对应的组件。
//这里的作用是同一在一个地方加载组件文件,不用每个组件都要写一次加载流程。
import Vue from 'vue'
import {
importAllVueFile } from '@/utils/common.js'
const routeModules = importAllVueFile(
require.context('./modules', false, /\.vue$/)
)
routeModules.forEach(({
camelModuleName, module }) => {
Vue.component("xxx-" + camelModuleName, module)
})
common.js文件:
//读取文件的文件,处理文件名
const jsFileNameRE = /^\.\/([^\s]+)\.js$/
const vueFileNameRE = /^\.\/([^\s]+)\.vue$/
export function importAllJsFile(modulesContext) {
return modulesContext.keys().map((modulesPath) => {
const moduleName = modulesPath.match(
jsFileNameRE
)
return {
moduleName,
camelModuleName: moduleName[1].replace(
/-(\w)/g,
(_, c) => (c ? c.toUpperCase() : '')
),
module: modulesContext(modulesPath).default
}
})
}
export function importAllVueFile(modulesContext) {
return modulesContext.keys().map((modulesPath) => {
const moduleName = modulesPath.match(
vueFileNameRE
)
return {
moduleName,
camelModuleName: moduleName[1].replace(
/-(\w)/g,
(_, c) => {
(c ? c.toUpperCase() : '')
}
),
module: modulesContext(modulesPath).default
}
})
}
下面是我自己写的组件,可能不适用全部情况,按需取
//柱状图
<template>
<v-chart
ref="bar_chart"
style="width: 100%;height: 100%;"
:options="orgOptions"
:initOptions="orgOptions"
:autoresize="true"
></v-chart>
</template>
<script>
import colorList from '@/utils/colorList';
export default {
data() {
return {
orgOptions: {
},
metricsSub: this.metrics,
colorList: colorList,
customColorSub: this.customColor,
XDimensionSub: this.XDimension,
legendShowCom: this.legendShow,
};
},
mounted() {
this.orgOptions = {
title: {
show: this.titleShow,
top: 40,
left: 60,
text: '哈哈哈'+ ': ' + this.unitName,
textStyle: {
fontStyle: 'lighter',
},
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow',
textStyle: {
align: 'left',
color: '#fff',
},
},
formatter: function(params, ticket, callback) {
let newParams;
let tooltipString = [];
newParams = [...params];
newParams.sort((a, b) => {
return a.seriesName.localeCompare(b.seriesName);
});
let xLabel = params[0].name+"<br>";
tooltipString.push(xLabel);
let total = newParams.forEach((p) => {
const cont =
p.marker +
' ' +
p.seriesName +
': ' +
p.value +
'<br/>';
tooltipString.push(cont);
total = total + p.value;
});
return tooltipString.join('');
},
},
grid: {
borderWidth: 0,
top: '18%',
bottom: '10%',
width: '85%',
},
legend: {
show: this.legendShowCom,
x: this.b