1、最好创建分包,因为引入的资源较大,放在分包里方便代码上传。与主包并级存放。echarts资源去官网下载即可。
微信小程序中可以使用 ECharts 创建图表啦! | 微信开放社区
目录结构为:
app.json
"pages":[
"pages/index/index"
],
"subpackages": [
{
"root": "x1",
"pages": [
"pages/data-analysis/data-analysis"
]
}
],
2、data-analysis.json
{
"usingComponents": {
"ec-canvas": "../../ec-canvas/ec-canvas"
}
}
3、data-analysis.wxml
<ec-canvas id="lineCanvas" canvas-id="line-canvas" ec="{{ ecLine }}"></ec-canvas>
4、data-analysis.wxss
ec-canvas {
width: 100%;
height: 420rpx;
display: block;
}
5、data-analysis.js
具体参数配置可参照官网:Documentation - Apache ECharts
import * as echarts from '../../ec-canvas/echarts';
data: {
ecLine: {
lazyLoad: true // 延迟加载
},
},
onLoad: function (options) {
let that = this;
that.lineComponent = that.selectComponent('#lineCanvas');
that.init_line();
},
init_line: function () {
let that = this;
that.lineComponent.init((canvas, width, height, dpr) => {
// 初始化图表
const lineChart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr //解决小程序视图模糊的问题,必写
});
lineChart.setOption(that.getLineOption());
// 注意这里一定要返回 chart 实例,否则会影响事件处理等
return lineChart;
});
},
getLineOption: function () {
var that = this;
//return 请求数据
return {
tooltip: {
trigger: 'axis',
backgroundColor: '#fff',
textStyle:{
color:'#7E97B5'
}
// formatter: function(params) {
// console.log(params);
// return '';
// }
},
grid: {
top: '5%',
left: '3%',
right: '5%',
bottom: '5%',
containLabel: true
},
xAxis: {
type: 'category',
axisTick: {
show: false
},
axisLabel: {
color: '#7E97B5',
interval: 0,
},
axisLine: {
lineStyle: {
color: '#BFBFBF',
}
},
data: [10, 20, 30, 40, 50, 60, 70]
},
yAxis: {
type: 'value',
axisLabel: {
color: '#7E97B5',
},
axisLine: {
show: false
},
axisTick: {
show: false
},
splitLine: {
textStyle: {
color: "#BFBFBF",
},
},
},
series: [{
data: [40,100, 70, 30, 80, 60, 10],
type: 'line',
symbol: 'none',
smooth: true,
itemStyle: {
normal: {
color: '#1890FF',
lineStyle: {
width: 2
}
}
},
},{
data: [20,90, 80, 70, 80, 50, 30],
type: 'line',
symbol: 'none',
smooth: true,
itemStyle: {
normal: {
color: '#c918ff',
lineStyle: {
width: 2
}
}
},
}]
};
},
小tip:ec-canvas文件必须和需要引入这个文件页面在同一个包里哦~