vue 异步加载接口数据渲染echarts

本文介绍如何在Vue中使用async/await从接口获取数据并渲染ECharts饼图。通过在组件挂载后异步获取数据,然后设置图表选项来避免因数据未加载完成导致的渲染问题。此外,还提到了其他解决方法如定时器和$nextTick。
摘要由CSDN通过智能技术生成

 

之前的文章  https://blog.csdn.net/qq_38830964/article/details/110545637 中,有对echarts的基础使用有过阐述。

由于在实际使用环境中,通常的图表数据是后台经过聚合计算而来,所以本文主要整理一下如何从接口获取数据,并显示在图表上

由于vue渲染组件是在挂载的时候,所以当我们使用异步方法获取数据时,由于js同步异步任务执行的机制。可能在页面渲染时,异步数据还未请求到,导致图表渲染不成功。

此时,比较合理的解决办法,应该是使用 async/await 语法进行模拟同步请求。

 

代码如下:

以下代码是通过接口,获取一个饼图的数据

图表容器

 <div id="myChart2" :style="{ width: '400px', height: '300px' }"></div>

方法执行

 mounted() {
    this.getdata();
}

数据获取逻辑

 async getdata() {
      this.$echarts.init(document.getElementById("myChart2")).showLoading();
      await this.$axios.get("api/Base/GetRwsForNow").then((response) => {
        //console.log(response);
        if (response.data.result == "1") {
          //let contacts = response.data.seriesList;
          //this.pieData.push(contacts);
          //this.temp = contacts;
          // console.log(response)
          this.$echarts.init(document.getElementById("myChart2")).hideLoading();
          this.$echarts.init(document.getElementById("myChart2")).setOption(
            {
              title: { text: "任务情况" },
              tooltip: {},
              legend: {
                data: response.data.legendList,
              },
              //backgroundColor: "#2c343c", //设置全局背景颜色
              textStyle: {
                //全局文本样式
                // color: "rgba(255, 255, 255, 0.3)",
              },
              //设置视觉引导线
              lineStyle: {
                color: "rgba(255, 255, 255, 0.3)",
              },
              itemStyle: {
                //高亮样式
                emphasis: {
                  //color: "#c23531",
                  shadowBlur: 200,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
              series: {
                type: "pie",
                radius: "55%",
                //roseType: "angle", //南丁格尔图
                //this.pieData,

                data: response.data.seriesList,
                //[
                // { value: 2, name: "启用" },
                // { value: 1, name: "暂停" },
                //],
              },
            },
            true
          );
        }else{
          this.$ant_message.error(response.data.msg);
        }
      });

除了使用 async/await语法之外,还有很多其他的方法可以这种因为异步数据加载而导致数据未渲染的情况。比如使用定时器、$nextTick等,大家可以根据实际情况,自行选用。

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值