VUE2框架:Echarts渲染接口数据

总体思路:首先保证series中的data拿到了接口调回来的数据,然后获取新的数据后面再次初始化echarts即调用echarts .init(document.getElementById('mychart')) .setOption(this.option);

数据定义格式——vue2

data() {
  return {
    // 定义Echarts配置对象
    option: {},
  }
},
mounted() {
  //调用echarts初始化方法
  this.initEcharts();
},
beforeDestroy() {
  //组件销毁前要注销echarts实例,这一点不是所有场景都必需,但我个人觉得加上无害处
  echarts.init(document.getElementById('mychart')).dispose();
},
methods: {
  initEcharts() {
    this.option = {
      title: {
        text: this.echartsTitle,
        top: 30,
        left: 30,
        textStyle: {
          fontSize: 18,
          color: '#707070',
        },
      },
      tooltip: {
        trigger: 'item',
        textStyle: {
          fontSize: 14,
          color: '#707070',
          align: 'center',
        },
        borderColor: '#707070',
        formatter: '{b}<br />{d}%',
      },
      legend: {
        orient: 'vertical',
        top: '2%',
        left: '0%',
        itemWidth: 10,
        itemHeight: 10,
        borderRadius: 0,
        textStyle: {
          fontSize: 14,
        },
      },
      series: [
        {
          type: 'pie',
          center: ['60%', '50%'],
          radius: ['40%', '75%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 7,
            borderColor: '#fff',
            borderWidth: 3,
          },
          label: {
            show: false,
            position: 'outside',
          },
          emphasis: {
            label: {
              show: false,
              fontSize: 40,
              fontWeight: 'bold',
            },
          },
          //data设为空数组,之后调用接口获取数据再赋值。
          data: [],
        },
      ],
    };
    const chartDom = document.getElementById('mychart');
    const myChart = echarts.init(chartDom);
    myChart.setOption(this.option);
    window.addEventListener('resize', () => {
      myChart.resize();
    });
  },
  
  //接口调用方法
  bjkkPercentRequest() {
    request({
      method: 'GET',
      url: '/polar/bjkk/data/analysis',
    }).then((res) => {
      if (res.status === 200) {
        if (res.data.code === 200) {
          let re = [];
          res.data.data.forEach((item) => {
            re.push({ value: parseFloat(item.percent), name: item.country });
          });
          //获取处理之后的数据并赋给echarts
          this.option.series[0].data = re;
          //echarts拿到值之后一定要再初始化一遍。数据有更新则后面要再初始化echarts图
          echarts
            .init(document.getElementById('mychart'))
            .setOption(this.option);
        }
      }
    });
  },
},

vue3与vue2思路相同,但要注意区别生命周期函数、vue3的setup形式和vue2的实例形式。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值