微信小程序使用echarts异步请求数据

// packageSesame/pages/dashboard/dashboard.js
// 引入echatrts
import * as echarts from '../../../utils/ec-canvas/echarts.js'

const app = getApp();
// 引入http接口
const { getDashboard } = require('../../service/reportForm.js').RFurl;
const HttpRequest = require('../../../utils/http.js').Http;

var SalesChart = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    salesCharts: {
      lazyLoad: true
    },
    formData: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.salesEchartsComponnet = this.selectComponent('#mychart-dom-bar-sales'); //id要写对,跟页面echarts id保持一致
    this.getData()
  },
  // 获取仪表盘数据
  getData() {
    var that = this;
    // 调接口
    var urlObj = getDashboard(that.data.timeIndex);
    HttpRequest.ajax({
      urlObj: urlObj,
      success: function (res) {
        if (res.code == '0') {
          that.setData({
            formData: res.data
          })
          that.init_echarts_sales();
        } else {
          app.showToastBox(res.msg || '获取失败')
        }
      }
    });
  },

  //全国连锁门店销售额初始化图表
  init_echarts_sales: function () {
    if (this.salesEchartsComponnet) {
      this.salesEchartsComponnet.init((canvas, width, height, dpr) => {
        // 初始化图表
        SalesChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        this.setOptionSales(SalesChart);
        // 注意这里一定要返回 chart 实例,否则会影响事件处理等
        return SalesChart;
      });
    }
  },
  setOptionSales: function (SalesChart) {
    SalesChart.clear(); // 清除
    SalesChart.setOption(this.getOptionSales()); //获取新数据
  },
  getOptionSales: function () {
    var that = this;
    var option = {
      color: ["#ff9e40"],
      title: {
        text: '近6个月销售额走势(单位,百万)',
        left: 'center',
        textStyle: {
          fontSize: 14,
        },
      },
      axisLabel: {
        interval: 0,
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: that.data.formData.totalStoreSalesTagList
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [{
        type: 'line',
        data: that.data.formData.totalStoreSalesDataList
      }]
    };
    return option;
  }
})

你可能感兴趣的:(echarts,微信小程序)