由于在项目开发过程中使用echarts组件,所以在空余时间总结echarts组件的常用配置,并实现图表随窗口大小自适应效果
<template>
<div style="width: 100%; height: 100%">
<div ref="chart" style="width: 100%; height: 100%"></div>
</div>
</template>
<template>
<div style="width: 100%; height: 100%">
<div ref="chart" style="width: 100%; height: 100%"></div>
</div>
</template>
<script>
export default {
data() {
return {
myChart: "",
XData: [],
lineData1: [],
lineData2: [],
};
},
mounted() {
this.getEchartData();
window.addEventListener("resize", this.echartResize);
},
methods: {
echartResize() {
this.myChart.resize();
},
getEchartData() {
const chart = this.$refs.chart;
if (chart) {
this.myChart = this.$echarts.init(chart);
const option = {
title: {
text: "折线图案例", //图标标题
left: "center", //标题位置-居中
},
//提示框组件
tooltip: {
trigger: "axis",
},
//图例配置
legend: {
top: "8%",
textStyle: {
//文字颜色
color: "#0f0",
},
},
//绘图区域配置
grid: {
show: true,
left: "6%",
right: "12%",
bottom: "3%",
containLabel: true,
backgroundColor: "#eee",
},
//工具栏
toolbox: {
top: "16%",
right: "6%",
orient: "vertical",
feature: {
//数据视图工具
dataView: {
readOnly: true,
backgroundColor: "rgba(146, 37, 37, 1)",
textareaColor: "rgba(29, 93, 153, 1)",
textColor: "rgba(233, 15, 208, 1)",
},
//数据区域缩放
dataZoom: {
yAxisIndex: "none",
},
//动态类型切换
magicType: {
type: ["line", "bar"],
},
//配置项还原
restore: {},
//保存为图片
saveAsImage: {},
},
iconStyle: {
borderColor: "rgba(21, 29, 134, 1)",
},
},
//区域缩放配置信息
dataZoom: {
type: "inside",
},
//X轴配置
xAxis: {
type: "category",
name: "时间/天",
nameTextStyle: {
color: "rgba(229, 8, 8, 1)",
},
nameGap: 4,
axisLine: {
lineStyle: {
color: "rgba(97, 12, 12, 1)",
},
},
axisLabel: {
show: true,
color: "rgba(195, 34, 34, 1)",
fontSize: 13,
},
data: this.XData,
},
//Y轴配置
yAxis: {
type: "value",
name: "数量/个",
nameLocation: "middle",
nameTextStyle: {
color: "rgba(47, 18, 194, 1)",
},
nameGap: "40",
axisLine: {
show: true,
lineStyle: {
color: "rgba(18, 61, 216, 1)",
},
},
},
// 数据配置
series: [
{
name: "折线一", //线的名字
type: "line", //显得类型
symbol: "none", //是否显示拐点
smooth: true, //拐点是否圆润
//拐点属性
itemStyle: {
color: "#f00",
},
//线的属性
lineStyle: {
color: "#f00", // 线的颜色
width: 2, //线的宽度
type: "dashed", //线的类型
},
data: this.lineData1,
},
{
name: "折线二", //线的名字
type: "line", //显得类型
symbol: "none", //是否显示拐点
smooth: true, //拐点是否圆润
//拐点属性
itemStyle: {
color: "#00f",
},
//线的属性
lineStyle: {
color: "#00f", // 线的颜色
width: 2, //线的宽度
type: "dashed", //线的类型
},
data: this.lineData2,
},
],
};
this.myChart.setOption(option);
}
},
},
created() {
let x = [];
let line1 = [];
let line2 = [];
for (let i = 0; i < 20; i++) {
x.push(i);
line1.push(Math.floor(Math.random() * (500 - 200 + 1)) + 200);
line2.push(Math.floor(Math.random() * (600 - 400 + 1)) + 400);
}
this.lineData1 = line1;
this.lineData2 = line2;
this.XData = x;
},
beforeDestroy() {
window.removeEventListener("resize", this.echartResize);
},
};
</script>