微信小程序云平台开发-echarts图表数据获取

2018-12-28  本文已影响0人  小岛wink

今天在学习在小程序中添加echarts图表的例子,之前练的都是静态图,添加好js很好实现,在学习云平台数据库相关的东西后,我试着把图表的数据从数据库中获取,实现动态展示图表数据。
以下是在项目中添加静态echarts图表的过程:

1、与pages目录同级,添加ec-canvas文件夹,里面包含echarts的js文件,可根据项目需要,定制你需要的图表类型的js,定制的地址在上一个博文中;

image.png

.wxml

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

.js相关代码

import * as echarts from '../../ec-canvas/echarts.js'
let chart = null;
var option = {
  color: ['#37a2da', '#32c5e9', '#67e0e3'],
  tooltip: {
    trigger: 'axis',
    axisPointer: {            // 坐标轴指示器,坐标轴触发有效
      type: 'shadow'        // 默认为直线,可选为:'line' | 'shadow'
    },
    confine: true
  },
  legend: {
    data: ['热度']
  },
  grid: {
    left: 20,
    right: 20,
    bottom: 15,
    top: 40,
    containLabel: true
  },
  xAxis: [
    {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }
  ],
  yAxis: [
    {
      type: 'category',
      axisTick: { show: false },
      data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisLabel: {
        color: '#666'
      }
    }
  ],
  series: [
    {
      name: '热度',
      type: 'bar',
      label: {
        normal: {
          show: true,
          position: 'inside'
        }
      },
      data: [300, 270, 340, 344, 300, 320, 310],
      itemStyle: {
        // emphasis: {
        //   color: '#37a2da'
        // }
      }
    }
  ]
};
//图表
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

.wxss样式

.container{
  padding-top:80rpx;
  width:100%;
  height:600rpx
}
ec-canvas {
  width: 100%;
  height: 100%;
}

.json

{
  "usingComponents": {
    "ec-canvas": "../../ec-canvas/ec-canvas"
  }
}

实现效果如下:


image.png

2、数据动态从数据库中获取,打开云开发控制台-数据库,添加集合chart,字段包含名称name和数量num。


image.png

js代码修改:


image.png
//图表
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  const db = wx.cloud.database({});
  const cont = db.collection('chart');
  cont.get({
    success(res) {
      console.log(res.data) 
      const name=[];
      const num=[];
      for(var i=0;i<res.data.length;i++){
        name.push(res.data[i].name);
        num.push(res.data[i].num);
      }
      option.yAxis[0].data=name;
      option.series[0].data=num;
      chart.setOption(option);
      return chart;
    }
  })
}

实现效果为:


image.png

3、过程中遇到获取不到数据的问题,test集合是之前做上传数据时添加的数据,这里就可以正常获取,但chart就获取不到:


image.png

解决方法为修改权限,改为第一个选项,则可以正常获取:


image.png
上一篇 下一篇

猜你喜欢

热点阅读