The use of echart in small programs

I have read many articles on the Internet and can run directly by copying them according to the official documents. I did not see how to build a chart after requesting the interface number in the applet. The following is my own writing by requesting data to set the data rendering chart. (Because I haven't touched this thing, I hope there is better code optimization or the wrong place can leave a message and tell me ha)


  1. Download at https://github.com/ecomfe/echarts-for-weixin
  2. Put the ec-canvas directory in the downloaded file in the applet project directory.
  3. Create a new page
  4. json
 {
  "usingComponents": {
    "ec-canvas": "../../ec-canvas/ec-canvas"
  }
}
  1. wxml
 <view class="container">
  <view class="echart-title">全国疫情新趋势</view>
  <ec-canvas 
    class="mapchart"   
    id="mapchart" 
    canvas-id="mapchart" 
    ec="{
   
   { ec }}">
   </ec-canvas>
</view>
  1. wxss
 .container { 
  padding: 15rpx;
  margin: 15rpx 0rpx;
  width: 100%;
  height: 50%;
  box-sizing: border-box;
}
.mapchart{
  width: 100%;
  height: 100%;
}
  1. js
import * as echarts from '../../ec-canvas/echarts'; //引入echarts.js
var dataList = [];
Page({
	/**
 1. 页面的初始数据
   */
  data: {
    ec: {
      lazyLoad: true // 延迟加载
    },
  },
  /**
 2. 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.echartsComponnet = this.selectComponent(".mapchart");
    this.getData(); //获取数据
  },
  getData: function () {
  	/**
  	 * 此处的操作:
  	 * 获取数据json
  	 */
  	wx.request({
  	  url: 'https://www.baidu.com', //仅为示例,并非真实的接口地址
      data: {},
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        // 设置数据
      	dataList =  [820, 932, 901, 934, 1290, 1330, 1320],
  		this.init_echarts();//初始化图表
      }
	});
  },
  //初始化图表
  init_echarts: function () {
    console.log(this.echartsComponnet)
    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: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data:dataList,
            type: 'line'
        }]  
    }
    return option;
  },
 
})
  1. Page effect
    Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41988554/article/details/107382434