微信小程序中Echarts数据异步更新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014465934/article/details/82960766

就是微信小程序中使用echarts-for-weixin

echarts-for-weixin的GitHub地址:https://github.com/ecomfe/echarts-for-weixin

1.wx.request

首先讲讲wx.request的使用:

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})

具体可参考:
https://developers.weixin.qq.com/miniprogram/dev/api/network-request.html#wxrequestobject
https://zhuanlan.zhihu.com/p/26991549

2.微信小程序使用echarts-for-weixin异步更新数据

后端代码:

router.all('/echarts',function (req,res) {

    // 连接到mysql
    var connection = mysql.createConnection({      //创建mysql实例
        host:'127.0.0.1',
        port:'3306',
        user:'root',
        password:'',
        database:'test'
    });
    connection.connect();
    var sql = 'SELECT * FROM tvalues1';

    // 转换格式
    var i;
    jsonData = {}
    xdays = []
    yvalues = []

    connection.query(sql, function (err,result) {
        if(err){
            console.log('[SELECT ERROR]:',err.message);
        }
        //str1 = JSON.stringify(result);
        //str = JSON.parse(str1);
        //数据库查询的数据保存在result中,但浏览器并不能直接读取result中的结果,因此需要用JSON进行解析
        //console.log(result);   //数据库查询结果返回到result中
       // console.log(str);
        //console.log(str1);
        /* str数据(json格式):
        *[{"id":1,"tdsvalue":"31"},{"id":2,"tdsvalue":"42"},{"id":3,"tdsvalue":"23"},
        * {"id":4,"":"44"},{"id":5,"tdsvalue":"55"},{"id":6,"tdsvalue":"36"}]
        * result/str1数据是 [ { id: 1, tdsvalue: '37' },{ id: 2, tdsvalue: '19' },{ id: 3, tdsvalue: '18' },
        * { id:4,tdsvalue: '17' }, { id: 5, tdsvalue: '17' }, { id: 6, tdsvalue: '15' },
        * { id: 7, tdsvalue: '16' },{ id: 8, tdsvalue: '17' },{ id: 9, tdsvalue: '18' } ]
        * */
        console.log(result);
        // 想要转换的格式:{ xdays: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],yvalues: [ '37', '19', '18', '17', '17', '15', '16', '17', '18' ] }
 
        for(i=0;i<result.length;i++){

            xdays.push(result[i].id);
            yvalues.push(result[i].tdsvalue);

        }

       // console.log('1x'+xdays);
        //console.log('1y'+yvalues);

        jsonData['xdays']=xdays;
        jsonData['yvalues'] = yvalues;

        res.send(jsonData);
        
       // console.log(jsonData);
      //  console.log(jsonData.xdays);
       // console.log(typeof(jsonData.xdays));
       // console.log(jsonData.yvalues);
      //  console.log(typeof(jsonData.yvalues));
       // console.log(typeof(jsonData));
    });
    connection.end();
});

后端是用Nodejs的Express框架,主要是连接数据库,取出数据,然后数据格式转换,其中很多注释是为了弄清楚数据格式。

index.js

import * as echarts from '../../ec-canvas/echarts'; //引入echarts.js
var dataList = [];

var app1 = {
  xday: [],
  yvalue: []
};

Page({
	/**
   * 页面的初始数据
   */
  data: {
    ec: {
      lazyLoad: true // 延迟加载
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.echartsComponnet = this.selectComponent('#mychart-dom-line');
    this.getData(); //获取数据
  },
  getData: function () {
  	/**
  	 * 此处的操作:
  	 * 获取数据json
  	 */
    wx.request({
      url: 'http://localhost:3000/users/echarts', //仅为示例,并非真实的接口地址
      method: 'get',
      data:{},
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {

		// 返回的res.data为{ xdays: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],yvalues: [ '37', '19', '18', '17', '17', '15', '16', '17', '18' ] }
        console.log(res.data);

        console.log("数据传输成功");

        app1.xday = res.data.xdays;
        app1.yvalue = res.data.yvalues;

        console.log(app1.xday);
        console.log(app1.yvalue);

        this.init_echarts();//初始化图表
      }
    });
  },
  //初始化图表
  init_echarts: function () {
    this.echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      Chart.setOption(this.getOption());
      // 注意这里一定要返回 chart 实例,否则会影响事件处理等
      return Chart;
    });
  },
  getOption: function () {

    // 指定图表的配置项和数据
    var option = {
      xAxis: {
        data: app1.xday
      },
      yAxis: {

      },
      series: [{
        data: app1.yvalue,
        type: 'line'
      }]
    }
    return option;
  },

})

index.json

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

index.wxml

<!--index.wxml-->
<view class="container">
  <ec-canvas id="mychart-dom-line" canvas-id="mychart-line" ec="{{ ec }}"></ec-canvas>
</view>

index.wxss

/**index.wxss**/
ec-canvas {
  width: 100%;
  height: 100%;
}

上面文件的目录结构是在小程序的pages/lines下面,主要代码时在index.js中。

结果图:

在这里插入图片描述

还有几个可以参考的文章:
https://blog.csdn.net/soul_wh/article/details/81027141
https://blog.csdn.net/hao_0420/article/details/80931339
https://blog.csdn.net/weixin_42416141/article/details/81028876
http://www.cnblogs.com/cnzlz/p/9245189.html#top

猜你喜欢

转载自blog.csdn.net/u014465934/article/details/82960766