第一步:安裝echarts
npm install echarts --save
第二步:頁面中引入
import echarts from "echarts";
第三步:定義具備高寬的DOM容器
<div id="chartLineBox" style="width: 90%;height: 70vh;"> </div>
第四步:echarts.init 方法初始化一個 echarts 實例並通過 setOption 方法生成一個簡單的折線圖
注意:這里只是在mounted中生成,實際項目中會在通過接口獲取數據后生成圖表
(可以在methods中設置方法,在點擊事件中調用此方法,什么改變就把什么當成參數)
// 折線圖方法,這個是在完成上個接口后就調用這個方法
getrr(time, data, name) {
console.log(name);
this.chartLine = echarts.init(document.getElementById("myChart"));
// 指定圖表的配置項和數據
var option = {
tooltip: {
//設置tip提示
trigger: "axis",
},
legend: {
//設置區分(哪條線屬於什么)
data: ["歷史值"],
textStyle: {
//圖例文字的樣式
color: "#FFFFFF",
fontSize: 12,
},
},
color: ["#f04e4e"], //設置區分(每條線是什么顏色,和 legend 一一對應)
xAxis: {
axisPointer: {
lineStyle: {
color: "#eeeeee",
width: 2,
},
label: {
backgroundColor: "#eeeeee",
},
},
//設置x軸
type: "category",
boundaryGap: false, //坐標軸兩邊不留白
data: time,
name: "時間", //X軸 name
nameTextStyle: {
//坐標軸名稱的文字樣式
color: "#eeeeee",
fontSize: 12,
padding: [0, 0, 0, 20],
},
// X軸坐標文字顏色
axisLabel: {
show: true,
textStyle: {
color: "#FFFFFF", //這里用參數代替了
},
},
axisLine: {
//坐標軸軸線相關設置。
lineStyle: {
color: "#4a4a4a",
},
},
},
yAxis: {
name: name,
nameTextStyle: {
color: "#FFFFFF",
fontSize: 12,
padding: [0, 0, 10, 0],
},
axisLine: {
lineStyle: {
color: "#4a4a4a",
},
},
axisTick: {
//y軸刻度線
show: false,
},
splitLine: {
//網格線
// "show": false,
lineStyle: { color: "#4a4a4a" },
},
type: "value",
// 改變y軸文字顏色
axisLabel: {
textStyle: {
color: "#ffffff",
},
},
},
series: [
{
name: "歷史值",
data: data,
type: "line", // 類型為折線圖
// 將折線圖改成平滑的曲線
// smooth: true,
lineStyle: {
// 線條樣式 => 必須使用normal屬性
normal: {
color: "#f04e4e",
},
},
// 添加橫線的漸變的背景圖
// areaStyle: {
// color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
// {
// offset: 0,
// color: "rgba(3,196,187,0.5)",
// },
// {
// offset: 1,
// color: "rgba(3,196,187,0.1)",
// },
// ]),
// },
},
// {
// name: "耗電量",
// data: this.historyList.dian,
// type: "line", // 類型為折線圖
// // 將折線圖改成平滑的曲線
// smooth: true,
// lineStyle: {
// // 線條樣式 => 必須使用normal屬性
// normal: {
// color: "#99f6f3",
// },
// },
// // 添加橫線的漸變的背景圖
// areaStyle: {
// color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
// {
// offset: 0,
// color: "rgba(153,246,243,0.5)",
// },
// {
// offset: 1,
// color: "rgba(153,246,243,0.1)",
// },
// ]),
// },
// },
// {
// name: "耗燃氣",
// data: this.historyList.qi,
// type: "line",
// // 將折線圖改成平滑的曲線
// smooth: true,
// lineStyle: {
// normal: {
// color: "#056966",
// },
// },
// // 添加橫線的漸變的背景圖
// areaStyle: {
// color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
// {
// offset: 0,
// color: "rgba(5,105,102,0.5)",
// },
// {
// offset: 1,
// color: "rgba(5,105,102,0.1)",
// },
// ]),
// },
// },
],
};
// 使用剛指定的配置項和數據顯示圖表。
this.chartLine.setOption(option);
},
后台接口傳的參數格式:
res:{
code:0,
data:{
shui:[3,4,5,6,7,8,9],
qi:[33,44,55,66,77,88,99]
time:[2021-02-04,2021-02-05,2021-02-06,2021-02-07,2021-02-08,2021-02-09,2021-02-10]
}
}