VUE+ECharts fazendo gráficos de pizza

A página inicial do projeto precisa implementar um gráfico de pizza (a interface de back-end retorna dados)

Preparação: primeiro instale echarts no projeto

cnpm install echarts --s

Então eu o introduzi em main.js

import echarts from 'echarts' // 引入echarts

Vue.prototype.$echarts = echarts

A seguir está a implementação específica da página

Seção da página HTML

 <!--客户报表-->
        <div class="pieBox" style="margin-right: 33px">
          <div class="title">
            <span class="s_tit">客户报表</span>
            <span class="s_English">Customer report</span>
          </div>
          <!-- 为 ECharts 准备一个具备大小(宽高)的 容器 -->
          <div style="display: flex">
            <div id="pieChart" class="pieSty"></div>
            <div class="wenzi">
              <template v-for="(item, index) in arrpie">
                <div class="pieNum" :key="index">
                  <span
                    :class="
                      index == 0
                        ? 'num1'
                        : index == item.length - 1
                        ? 'num3'
                        : 'num2'
                    "
                    >{
   
   { item.productName }}</span
                  ><span>{
   
   { item.customerNum }}</span>
                </div>
              </template>
            </div>
          </div>
        </div>

Requisitos parciais do projeto:

Ele é exibido de acordo com o estilo necessário (índice == 0 usa estilo num1, a primeira coluna (aqui se refere ao número total de clientes no diagrama de interface do usuário), quando o subscrito for igual ao último número, use num3 e use num2 para o resto),

{ { item.productName }} é o nome à direita e { { item.customerNum }} é o número.

O seguinte é o formato de dados fornecido pela interface de back-end, portanto, é convertido em uma string no método getAPui()

{
    "code": 200,
    "message": "获取成功",
    "dataInfo": [
        {
            "customerNum": 1,
            "productName": "客户总数",
            "ratio": 0
        },
        {
            "customerNum": 1,
            "productName": "某某系统",
            "ratio": 100
        }
    ]
}

parte js 

<script>
import { getCustomerReport } from "../../../api/api";//引入接口
import session from '../../../until/loginIntercept/loginIntercept'
export default {
  name: 'hello',
  data() {
    return {
      arrpie: [],//饼图
    }
  },
  mounted() {
    this.getAPui();//饼图-数据
  },
  methods: {
    /**
     * 饼图-数据 这里处理接口拿到的数据
     */
    getAPui() {
      getCustomerReport({ "supplierId": session.getLoginInfo().supplierId }).then(res => {
        if (res.data.code = 200) {
          var str = JSON.stringify(res.data.dataInfo);//JSON.stringify转字符串 左边饼图用的
          str = str.replace(/productName/g, 'name');//接口返回的productName 替换成name
          str = str.replace(/ratio/g, 'value');//接口返回的ratio 替换成value
          var arr = JSON.parse(str);
          this.arrpie = res.data.dataInfo;//左边饼图用
          arr.splice(0, 1);//arr.splice(开始删除下标,删除个数),因为客户总数不需要显示在左边饼图上
          this.drawLine(arr);//处理好的数据传给drawLine方法
        }
      })
    },
    /**
     * 饼图-样式
     */
    drawLine(arr) {
      // 基于准备好的dom,初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById('pieChart'))
      // 绘制图表
      myChart.setOption({
        color: ['#5d88ff', '#9071fc', '#ffa05e', '#ffc85e', '#ff5f5d', '#63dfff'],//配置颜色
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            label: {
              position: 'inner',
              fontSize: 14,
              formatter: '{d}%'//设置左边图上的%
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: arr //接收getAPui()方法的数据
          }
        ]
      });
    },
  }
}
</script>

 seção css (estilos desta seção)

<style scoped>
.s_tit {
  font-size: 18px;
  font-weight: 600;
  letter-spacing: 2px;
}
.s_English {
  color: #d3cece;
  font-size: 14px;
}
.pieBox {
  width: 48%;
  height: 355px;
  box-shadow: 1px 1px 5px 1px #e3e3e3;
}
.title {
  width: 90%;
  height: 25px;
  padding: 15px 20px 10px 7px;
  margin: 0px 0px 0px 10px;
  border-bottom: 1px solid #e8e8ed;
}
.pieSty {
  width: 50%;
  height: 240px;
  top: 30px;
}
.wenzi {
  width: 50%;
  padding: 57px 0px 0px 0px;
  display: flex;
  flex-direction: column;
}
.pieNum {
  margin: 15px 0px;
}
.num1 {
  font-weight: 600;
  margin-right: 75px;
  letter-spacing: 19px;
}
.num2 {
  margin-right: 89px;
  letter-spacing: 19px;
}
.num3 {
  margin-right: 89px;
  letter-spacing: 19px;
}

Acho que você gosta

Origin blog.csdn.net/RemindingMe/article/details/123335797
Recomendado
Clasificación