taro 开发小程序的时候遇到一个饼图的业务需求
1. 下载微信小程序版echarts 到项目里
微信小程序版echarts
https://github.com/ecomfe/echarts-for-weixin
echarts.js 文件可能过大导致无法编译 可以根据自己需求去定制 https://echarts.apache.org/zh/builder.html
2. 页面引入
import echarts from "../../component/ec-canvas/echarts";
usingComponents: { 'ec-canvas': '../../component/ec-canvas/ec-canvas' // 书写第三方组件的相对路径 }
3. 配置
list.jsx
import Taro, { Component } from '@tarojs/taro'import { View, Text } from '@tarojs/components'import echarts from "../../component/ec-canvas/echarts"; import './list.scss'let pieDataA = null; export default class List extends Component { constructor (props) { super(props) this.state = { ec: { onInit: function (canvas, width, height) { pieDataA = echarts.init(canvas, null, { width: width, height: height }); canvas.setChart(pieDataA); return pieDataA; } } } } config = { navigationBarTitleText: 'taro echarts', usingComponents: { 'ec-canvas': '../../component/ec-canvas/ec-canvas' // 书写第三方组件的相对路径 } } componentWillMount () { let dataA = ['西凉', '益州', '兖州', '荆州']; let dataValA = [ {value: 1548,name: '幽州啊啊'}, {value: 535, name: '荆州'}, {value: 510, name: '兖州'}, {value: 634, name: '益州'} ]; setTimeout(() => { pieDataA.setOption(this.getOption(dataA,dataValA)); },1000); } componentDidMount () { } getOption(data,dataVal){ let option = { animation: false, tooltip: { trigger: 'item', formatter: '{c} ({d}%)' }, legend: { bottom: 0, left: 'center', data: data }, color:['#3AA1FF', '#36CBCB', '#FBD437', '#4ECB73'], series: [ { type: 'pie', radius: '65%', center: ['50%', '50%'], data: dataVal } ] }; return option; } initChart(canvas, width, height){ const chart = echarts.init(canvas, null, { width: width, height: height }); canvas.setChart(chart); chart.setOption(this.state.option); return chart; } render () { return ( ) } }
list.scss
一定要注意css (ec-canvas外层没有设置高度宽度的块级元素包裹是出不来的)
.mychart-con{ width: 750px; height: 550px; margin: 0 auto; } ec-canvas { width: 100%; height: 100%; }
4.效果图
至此大功告成!