主要記錄echarts中的坑,基本的使用就不詳細說了,隨便百度都有。。。
先是異步請求數據渲染echarts的方法,踩坑在最后!!!
第一步首先引入echarts
echarts官網沒有小程序版,不過已經有人在github發布echarts的小程序版本了。。但是echarts.js的版本不是最新的,個人推薦去官網在線定制。定制版的echarts體積更小,而且小程序中用到的圖表種類不會很多,而且定制非常簡單,一定要去自己定制,然后替換掉他的echarts.js。
首先,下載echarts微信版 地址: https://github.com/ecomfe/echarts-for-weixin
將下載好的文件中 ec-canvas目錄 放在小程序項目根目錄中即可。
然后就是在json、js中引入,
異步請求數據
wxml中在wxml中一定要給echarts的容器設置高度
<view class="workLine">
<ec-canvas id="lessonChart" canvas-id="mychart-line" ec="{{ lessonLine }}"></ec-canvas>
</view>
首先 建立一個全局變量(注意,放在page外面,要全局變量,方便修改),
var lessonMonthArr = [];
var lessonCountArr = [];
var lessonChart = null;
在data中設置延遲加載
lessonLine: {
lazyLoad: true
}
在異步請求中,去調用初始化echarts的函數
getLesson() {
app.fetch(Api.lessonRecordData, {
officeId: this.data.adminInfo.officeId,
}, "GET", res => {
var arr = res.data.data.monthData
var num = 0;
var _data = [];
var proportion = 4;
for (let i = 0; i < arr.length; i++) { //for循環是自己處理的數據
if (i % proportion == 0 && i != 0) {
_data.push(arr.slice(num, i));
num = i;
}
if ((i + 1) == arr.length) {
_data.push(arr.slice(num, (i + 1)));
}
}
this.setData({
lessonData: _data,
lessonTotal: res.data.data.total
})
//重要的是這兩步, 因為如果頁面加載過,全局變量中的值並不會消失,所以我先清空一下全局變量
lessonMonthArr = [];
lessonCountArr = [];
//然后去給這兩個全局變量賦值
arr.forEach((item) => {
lessonMonthArr.push(item.month + "月");
lessonCountArr.push(item.count);
})
//去調用初始化函數
this.init_lessonChart()
初始化函數
//課堂折線圖
init_lessonChart() {
this.lessonChartComponnet = this.selectComponent('#lessonChart'); //去獲取echarts 這里的id就是echarts的id
this.lessonChartComponnet.init((canvas, width, height) => {
// 初始化圖表 這個lessonChart 就是之前全局變量設置過的
lessonChart = echarts.init(canvas, null, { //echarts會繼承父元素的寬高
width: width,
height: height,
});
lessonChart.setOption(this.getLineOption()); //這一步是給echarts 設置數據及配置項
return lessonChart; //一定要return出去
});
},
設置配置項
//這里的配置項與pc端一樣
getLineOption(xData, data) {
var lineStyle = {
color: {
type: 'linear',
x: 0,
x2: 1,
colorStops: [{
offset: 0,
color: "#4a5e6b" // 0% 處的顏色
}, {
offset: 0.5,
color: '#5cd6cb' // 50% 處的顏色
},
{
offset: 1,
color: '#4a5e6b' // 100% 處的顏色
},
],
global: false // 缺省為 false
},
width: 4
}
var option = {
color: ["#73ffe4"],
tooltip: {
trigger: "axis",
position: function(pos, params, dom, rect, size) {
return [pos[0] - 35, '10%'];
}
},
grid: {
show: true,
borderColor: "transparent",
backgroundColor: bgcolor,
top: 30,
bottom: 20,
right: 0
},
textStyle: {
color: "#fff",
},
xAxis: {
type: 'category',
boundaryGap: true,
data: workMonthArr, //異步請求的數據
axisTick: {
alignWithLabel: true,
inside: true
},
axisLabel: {
align: "center",
fontSize: 10
},
axisLine: {
lineStyle: {
color: "#697082",
},
},
},
yAxis: {
x: 'center',
type: 'value',
name: "數量",
nameTextStyle: {
color: "#a4a4ae"
},
axisTick: {
show: false
},
splitLine: {
lineStyle: {
color: "#47516f"
}
},
axisLine: {
lineStyle: {
color: "#697082",
},
},
},
series: [{
type: 'line',
smooth: true,
data: workCountArr, //異步請求的數據
lineStyle
}]
};
return option;
},