vue中使用echarts
项目中经常会应用到
echarts
图表,这里再次记录下、方便使用。
- 众所周知
echarts
是非常强大的插件,千万级数据可视化渲染能力,涵盖各行业图表等等。
效果图
如何使用?
安装及引入echarts
- 安装
npm install echarts -S
- 引入方式
//全局引入
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
//局部【这里使用局部引入】
import echarts from "echarts";
绘制图表
-
创建
DOM
容器,并设置宽高 -
初始化
echarts
-
使用
创建DOM
容器
<div class="myChart" id="myChart" ref="myEchart" :style="{width: '100%', height: '200px'}">
</div>
初始化echarts
绘制图标及一些需要的配置参数
drawLines() {
// 基于准备好的dom,初始化echarts实例
this.chart = echarts.init(this.$refs.myEchart, {renderer: 'svg'});
// this.chart = echarts.init(document.getElementById('myChart'), {renderer: 'svg'})
// 绘制图表
this.chart.setOption({
title: {
// text: '使用echarts',
textStyle: {
fontWeight: "normal", //标题颜色
color: "#408829"
},
x: "center"
},
tooltip: {
trigger: "axis",
formatter: "时间 : {b}<br/>收益 : {c}元"
// 是否显示坐标轴指示线。
// axisPointer: {
// type: 'cross',
// label: {
// backgroundColor: 'red'
// }
// }
},
legend: {
// data: ['人数']
},
grid: {
top: "10%",
left: "4%",
right: "5%",
bottom: "0%",
containLabel: true
},
color: ["#9CBDFE"],
xAxis: [
{
splitLine: { show: false }, //每个区块分隔线
type: "category",
boundaryGap: false, //折线两边留白
data: [],
splitArea: { show: false }, //背景区块隔行变色
axisLine: {
lineStyle: {
//x轴颜色和字体大小
color: "#EBEBEB",
fontSize: "10"
}
},
axisLabel: {
show: true,
interval: "auto",
// rotate: "0",
textStyle: {
color: "#999" //文字颜色
}
}
}
],
yAxis: {
// 更改区域颜色
splitArea: {
// show: true,
// areaStyle: {
// color: 'red'
// }
},
type: "value",
// name: "日/元",
splitLine: {
lineStyle: {
//y轴参考线颜色,如果要隐藏,可设置为 color: "none"
color: "#EBEBEB",
type: "dashed"
}
},
axisLine: {
lineStyle: {
color: "#EBEBEB"
}
},
axisLabel: {
show: true,
interval: 0,
rotate: "0",
textStyle: {
color: "#999" //文字颜色
}
}
},
series: [
{
name: "",
type: "line",
smooth: true,
// 区域背景
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
[
{
offset: 0,
color: "rgb(156,189,254)"
},
{
offset: 1,
color: "rgb(255,255,255)"
}
]
)
},
data: [],
itemStyle: {
normal: {
lineStyle: {
color: "#5289F7"
}
}
}
}
]
});
},
使用
- 在
created
中请求数据
this.getInvestorSevenTrend();
- 在
mounted
生命周期中实例化echarts
对象
mounted() {
// 统计图
this.$nextTick(() => {
this.drawLines();
});
},
请求接口返回相关数据并赋值
echarts
图表中
getInvestorSevenTrend() {
let that = this;
this.axios.investorSevenTrend({}).then((res) => {
this.$toast.clear();
let datas = res.data;
if (parseInt(datas.code) != 200) {
this.$toast(datas.msg);
return;
}
let tempData = datas.data;
this.investorSevenList = tempData;
// 处理数据
let statisticDate = [];
let statisticTotal = [];
tempData.forEach((item, key)=> {
statisticDate.push(item.date);
statisticTotal.push(item.sumAmount);
})
// 填入数据
that.chart.setOption({
xAxis: {
data: statisticDate
},
series: [{
data: statisticTotal
}]
});
})
},
- 后端返回数据格式效果图