时间:2021-11-10 09:25:29 | 栏目:JavaScript代码 | 点击:次
先看下最终实现的效果?C自己做的小demo
首先到ECharts官网下载官网地址
根据上面的网址下载代码把ec-canvas文件拷贝下来放到你自己的项目中,
我放的是tool文件夹下面,你们随意引入的时候注意路径就行
然后在你需要用的页面引入,在json中加入,这里要注意路径echart.json
"usingComponents": { "tab":"../../component/tabs/tab", "ec-canvas":"../../tools/ec-canvas/ec-canvas" },
先把简单的布局和样式弄好echart.wxml
<view class="echart"> <tab active-tab="{{activeTab}}" period-list="{{periodList}}" bind:changePeriodType='changePeriodType'></tab> <view class="echart-position"> <ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar"></ec-canvas> </view> </view>
样式echart.wxss
.echart-position { position:relative; height: 280px; overflow:hidden; }
echart.js
先引入
import * as echarts from '../../tools/ec-canvas/echarts'; function setOption(chart,data){ var option = { title: { text: '' }, tooltip: { trigger: 'item' }, legend: { data: [] }, series: [{ name: '', type: 'pie', radius: ['40%', '70%'], avoidLabelOverlap: false, label: { show: false, position: 'center' }, emphasis: { label: { show: true, fontSize: '40', fontWeight: 'bold' } }, labelLine: { show: false }, data: [ ...data ] }] }; chart.setOption(option); return chart; } Page({ data: { periodList: [ { id: 'outcome', text: '支出' }, { id: 'income', text: '收入' }, ], activeTab: 'outcome', echartsData: null, // echarts 数据 }, // 收入支出切换事件 changePeriodType(e) { console.log(e, '<=收入支出切换事件') this.setData({ activeTab: e.detail.params.type }) // 重新查询列表 this.getEchartData(); }, // 查询收入支出数据 getEchartData() { wx.cloud.database().collection('spendD').where({ type: this.data.activeTab == 'outcome' ? 0 : 1 }).get().then(res => { let calcResult = this.handleOriginData(res.data); this.setData({ echartsData:calcResult }) this.init_one(calcResult) }) }, handleOriginData(array) { let result = []; let obj = {} array.forEach(item => { if (!obj[item.name]) { obj[item.name] = 0; } obj[item.name] += Number(item.amount); }) for(let key in obj){ let temp = {}; temp['name'] = key; temp['value']= obj[key]; result.push(temp); } console.log(result,'result') return result }, /** * 生命周期函数--监听页面加载 */ init_one: function (data) { //初始化图表 this.echartComponent.init((canvas, width, height) => { const chart = echarts.init(canvas, null, { width: width, height: height }); setOption(chart,data) this.chart = chart; return chart; }); }, onLoad: function (options) { this.getEchartData() }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { this.echartComponent = this.selectComponent('#mychart-dom-bar'); }, })
采坑tips 当按照教程配置好图没有预想出来时 注意添加下样式