ECharts如何调用接口获取后端数据

2023-06-09

这篇文章主要介绍了ECharts如何调用接口获取后端数据的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇ECharts如何调用接口获取后端数据文章都会有所收获,下面我们一起来看看吧。

方法一:在mounted中使用定时器调用eacharts方法(定时器可以获取到data中的数据)

mounted () {
    setTimeout(() => {
      this.axisOption() // 树状
      this.pieOption()//饼图
    }, 2000)
  },
//或者
mounted () {
    setTimeout(async () => {
      const res = await Getwx()
      this.Monthlist = res.Data.Monthlist
      this.Visitpvlist = res.Data.Visitpvlist
      this.drawLine();//柱状图
}, 0);
},

方法二:在调用数据的时候调用图表(一个页面的所有数据都在这一个接口中)

created () {
    this.GetProjectAll ()
  },
 
 methods: {
// 获取数据
    async GetProjectAll () {
      const res = await GetProjectAll({ projectid: this.formdata.type })
      this.tableData = res.data.jrgrsl.data
      this.pieData = res.data.clbp.data
      this.$nextTick(() => {
        this.axisOption() // 树状
        this.pieOption()//饼图
      })
    },
  }

方法三:使用chartes中的dataset数据集

<script>
import * as echarts from 'echarts'
import { getStatistics } from '@/api/home'
export default {
  data () {
    return {
      mainData: [],//折线图数据
    }
  },
  mounted () {
     this.chartSetting();
  },
  created () {
    this.CeData()
  },
  methods: {
    // 返回数据
    async CeData () {
      const { data } = await getStatistics()
      this.mainData = data.mainData
    },
    // 折现图
    chartSetting () {
      // 基于准备好的dom,初始化echarts实例
      this.mainChart = echarts.init(document.getElementById('main'))
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        dataset: [ // 数据
          {  source: this.mainData // 表数据 },
          { transform: {
              type: 'sort'
            }
          }
        ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLabel: { // 底部文字设置
              interval: 0, // 控制是否全部显示
              fontSize: 12
            },
            axisLine: { // 底部横线
              show: false
            },
            axisTick: { // 刻度线
              show: false
            }
          }
        ],
        yAxis: [
          { type: 'value' }
        ],
        series: [
          {
            name: '项目',
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {  width: 1,   color: '#2e3192' },
            showSymbol: false,
            label: {  show: true,  position: 'top' },
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {  offset: 0,  color: '#62a0f8' },
                {  offset: 1, color: '#b5d5ff' }
              ])
            },
            markPoint: { // 最大值和最小值标注
              data: [
                { type: 'max', name: '最大值' }
              ]
            },
            emphasis: {  focus: 'series' }
          }
        ]
      }
      // 绘制图表
      this.mainChart.setOption(option)
      const that = this
      window.addEventListener('resize', function () {
        that.mainChart.resize()
      })
    },
  }
}
</script>

方法四:在对应图表中,用ajax请求

 drawLine2 () {
      var chartDom = document.getElementById('main2');
      var myChart = echarts.init(chartDom);
      var option;
 
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: "11%",
          width: "80%",
          height: "60%"
        },
        legend: [{
          data: ['单位: 秒'],
          top: "10",
          left: "10",
          itemWidth: 8,
          itemHeight: 8,
          icon: "rect",
          textStyle: {
            color: "#fff"
          }
        }, {
          data: ['增速%'],
          top: "10",
          right: "5%",
          itemWidth: 8,
          itemHeight: 8,
          icon: "rect",
          textStyle: {
            color: "#fff"
          }
        }],
        xAxis: [
          {
            type: 'category',
            data: [],
            axisPointer: {
              type: 'shadow'
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              interval: 0,
              textStyle: {
                color: '#b8b8ba',
              },
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
            max: 10000,
            interval: 2000,
            axisLabel: {
              formatter: function (value) {
                return value + ""
              },
              textStyle: {
                color: '#b8b8ba',
              },
            },
            axisLine: {
              show: true
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: true,
              lineStyle: {
                width: 0.5
              }
            },
            symbol: "triangle"
          },
          {
            type: 'value',
            min: 0.4,
            max: 0.9,
            interval: 0.1,
            axisLabel: {
              formatter: '{value}',
              textStyle: {
                color: '#b8b8ba',
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                width: 0.5
              }
            },
          }
        ],
        series: [
          {
            name: '单位: 秒',
            type: 'bar',
            data: [],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#01c7f4' },
                { offset: 1, color: '#003fe2' }
              ]),
              borderRadius: 8
            },
            barWidth: 10
          },
          {
            name: '增速%',
            type: 'line',
            areaStyle: {},
            yAxisIndex: 1,
            data: [],
            itemStyle: {
              color: "#77ff3b",
            },
            lineStyle: {
              width: 1
            },
            symbolSize: 7,
            areaStyle: {
              opacity: 0.4,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 1, color: '#040d0c' },
                { offset: 0, color: '#5cd62c' }
              ])
            },
          }
        ]
      };
      const zoomSize = 6;
      myChart.on('click', function (params) {
        console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
        myChart.dispatchAction({
          type: 'dataZoom',
          startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue:
            dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
        });
      });
      option && myChart.setOption(option);
      $.ajax({
        type: "get",
        // async: false, //同步执行
        url: "api/WxStatistics/GetStatisticsData",
        data: {},
        success: function (result) {
          myChart.setOption({
            xAxis: { data: result.Data.Monthlist },
            series: [
              {
                data: result.Data.Staytimeuvlist,
              },
              {
                data: [0.6, 0.65, 0.65, 0.68, 0.58, 0.61, 0.58, 0.6, 0.61, 0.65, 0.63, 0.55],
              }
            ]
          })
        },
        error: function (errorMsg) {
          alert("不好意思,图表请求数据失败啦!");
          myChart.hideLoading();
        }
      })
      window.addEventListener("resize", function () {
        myChart.resize();
      });
    },

注意

如果一个图表需要展示不同数据时,每获取一次数据,图表都会重新渲染一次(例如下拉框中选取数据后,图表切换对应数据)。
可能会出现There is a chart instance already initialized on the dom.这样的警告,意思是dom上已经初始化了一个图表实例。
解决办法:可以在每次渲染前先销毁这个实例,然后再重新渲染。

var myChart //先注册全局变量
 
 axisOption () {
      //在方法内判断,然后销毁实例,然后再初始化
      if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
      }
      // 基于准备好的dom,初始化echarts实例
      myChart = echarts.init(document.getElementById('axisMain'))
      const option = { }
      // 绘制图表
      myChart.setOption(option)
      window.addEventListener('resize', function () {
        myChart.resize()
      })
    },

关于“ECharts如何调用接口获取后端数据”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“ECharts如何调用接口获取后端数据”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注本站行业资讯频道。

《ECharts如何调用接口获取后端数据.doc》

下载本文的Word格式文档,以方便收藏与打印。