当前位置: 首页>前端>正文

动态Echart

1.引入Echarts
(1)将ec-canvas文件拷贝下来放到你自己的项目中:
(2)在你需要使用Echarts的页面的json文件中引入Echarts

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

2.使用Echarts
在需要显示图表的页面的wxml中使用Echarts。

<view>
    <ec-canvas id="mychart-dom-line" canvas-id="mychart-line" ec="{{ ec }}" />
</view>

在wxss设置宽度和高度

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

3.js页面设置Echarts以及动态刷新
有三个注意的点:
1:独立option
2:onReady获取节点
3:更新数据:同时更新init和option

import * as echarts from "../utils/ec-canvas/echarts";
// 1、独立option
function setOptionData(chart, name1, name2, xdata, ydata) {
  const option = {
    tooltip: {...},
    legend: {
      data: [name1, name2],
      ...
    },
    xAxis: {
      data: xdata,
      ...
    },
    yAxis: {...},
    series: [
      {
        name: name2,
        type: "bar",
        ...
        data: ydata,
      }
    ],
  };
  chart.setOption(option);
}
Page({
    data:{
        ec: {
          onInit: null,
          lazyLoad: true
        }
    },
    onLoad(){
        this.getStatData()
    },
    onReady() {
        // 2、在页面渲染后拿到节点
        this.oneComponent = this.selectComponent('#mychart-dom-line');
    },
    getStatData(){
        const name1 = "name1"
        const name2 = "name2"
        const xdata = ['a','b','c']
        const ydata = [4,5,6]
        this.initChart(name1, name2, xdata, ydata)
    },
    initChart(name1, name2, xdata, ydata) {
        // 3、根据拿到的节点重新init 并 更新数据option
        this.oneComponent.init((canvas, width, height, dpr) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr // new
            });
            setOptionData(chart, name1, name2, xdata, ydata)
            this.chart = chart;
            return chart;
        });
    }
})

https://www.xamrdz.com/web/2nd1997574.html

相关文章: