十年河东,十年河西,莫欺少年穷
学无止境,精益求精
1、引入Echarts组件库,可参考:https://echarts.apache.org/handbook/zh/how-to/cross-platform/wechat-app/#%E5%9C%A8%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E4%B8%AD%E4%BD%BF%E7%94%A8-echarts
2、根据1的描述,下载GitHub文件包,鄙人已下载好,并放入了博客园主页中,下载地址:https://files.cnblogs.com/files/chenwolong/echarts-for-weixin-master.zip
示例代码,我随便放的目录如下:
3、新建小程序页面,Echars,并引入组件库,组件库大概500KB,因此,建议使用分包技术
Echars.json 中引入组件
{ "usingComponents": { "ec-canvas": "/utils/Echarts/ec-canvas/ec-canvas" } }
4、Echars.js 中引入主类库 ec-canvas/echarts.js
import * as echarts from '../../utils/Echarts/ec-canvas/echarts';// 数据
Echars.js 整体代码如下:
// pages/echarts/echarts.js import * as echarts from '../../utils/Echarts/ec-canvas/echarts';// 数据 var data = [{ X: "12日", Y: 100 }, { X: "13日", Y: 100 }, { X: "14日", Y: 100 }, { X: "15日", Y: 100 }, { X: "16日", Y: 100 }, { X: "17日", Y: 100 }, { X: "18日", Y: 100 }] // 存储住首次调用函数的参数 方便后续调用时传参取值 var unit = '%' var canvas1 = '' var width1 = '' var height1 = '' var dpr1 = '' function initChart(canvas, width, height, dpr) { canvas1 = canvas width1 = width height1 = height dpr1 = dpr const chart = echarts.init(canvas, null, { width: 375, height: height, devicePixelRatio: dpr }); canvas.setChart(chart); var option = { color: "#6c5ce7", tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, grid: { top: "8%", }, xAxis: [{ type: 'category', data: data.map(A => A.X), axisTick: { alignWithLabel: true } }], yAxis: [{ type: 'value' }], series: [{ name: 'Direct', type: 'bar', barWidth: '60%', data: data.map(A => A.Y), }] }; chart.setOption(option); return chart; //柱状图 } Component({ /** * 组件的属性列表 */ properties: { title: { type: String, value: "" } }, /** * 组件的初始数据 */ data: { ec: { onInit: initChart }, }, lifetimes: { attached: function () { // 在组件实例进入页面节点树时执行 this.GetData(); } }, /** * 组件的方法列表 */ methods: { GetData() { let that = this; let p = new Promise((resolve, reject) => { var result = [{ X: "12日", Y: 96 }, { X: "13日", Y: 92 }, { X: "14日", Y: 100 }, { X: "15日", Y: 90 }, { X: "16日", Y: 98 }, { X: "17日", Y: 99 }, { X: "18日", Y: 97 }]; resolve(result); }) .then((result) => { data = result; }) } } })