小程序使用echarts

参考文档:echarts官网echarts-for-weixin

  • 第一步引入组件库,可直接从echarts-for-weixin下载,也可以从echarts官网自定义生成,这里我们就不贴了
  • 组件库引入好后,就是页面引用啦,废话不多说,直接上代码

index.js:

import * as echarts from '../../components/ec-canvas/echarts'; // 这样引用可避免报init is undefined
let chart = {};
Page({
  data: {
    ec: {
      lazyLoad: true
    }
  },
  onLoad(options) {
      this.initChart(1)
  },
  // 初始化组件
  initChart(status) {
    const data = this.selectComponent("#mychart-dom-bar" + status)
    data.init((canvas, width, height) => {
      chart[status] = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: 2
      });
      canvas.setChart(chart[status]);
      this.setOption(status);
      return chart[status];
    })
  },
  setOption(i) {
    chart[i].clear(); // 清除
    chart[i].setOption(this['getOption' + i](), true); //获取新数据
  },
  getOption1() {
    return {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: 0,
        bottom: 0,
        top: 25,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['洗美', '贴膜', '改装', '改色'],
        axisTick: {
          show: false
        },
        axisLabel: {
          color: 'rgba(0,0,0,0.45)',
          fontWeight: 'bold',
          lineHeight: 14,
          padding: [10, 0, 19, 0]
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(0,0,0,0.15)'
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: 'rgba(0,0,0,0.45)',
          fontWeight: 'bold',
          lineHeight: 14,
          padding: [0, 8, 0, 0]
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(0,0,0,0.15)'
          }
        }
      },
      series: [{
        data: [120, 200, 150, 80],
        type: 'bar',
        color: '#0E71B2',
        label: {
          show: true,
          position: 'top',
          color: '#0E71B2',
          fontSize: 16
        }
      }]
    }
  },
})

index.wxml:

<view class="ec-container">
  <ec-canvas id="mychart-dom-bar1" canvas-id="mychart-bar1" ec="{
   
   {ec}}"></ec-canvas>
</view>

index.wxss:

.ec-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 600rpx;
  padding: 0 20rpx;
}

ec-canvas {
  width: 100%;
  height: 100%;
}

此方法也可封装为一个页面生成多个图表
欢迎大家留言指正!

猜你喜欢

转载自blog.csdn.net/qq_43384836/article/details/132008097