vue 把echarts封装成一个方法 并且从后端读取数据 +转换数据格式 =动态echarts 联动echarts表

1.把echarts 在 methods 封装成一个方法mounted 在中调用

折线图 和柱状图

mounted调用下边两个方法

复制代码
  mounted(){//最早获取DOM元素的生命周期函数 挂载完毕
    console.log('mounted-id' , document.getElementById('charts'))
      this.line()
      this.pie()
    },

methods里边的方法

复制代码
line() {
      // 基于准备好的dom,初始化echarts实例
      var myChart = echarts.init(document.getElementById('charts'));
      // 绘制图表
      myChart.setOption({
        tooltip: {//提示框组件
          trigger: 'axis',
        },
        legend: {},
        toolbox: {
          feature: {
            // dataZoom: {
            //   yAxisIndex: 'none'
            // },
            // restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {//x轴数据
         data: [120, 200, 150, 80, 70, 110, 130],
        },
        yAxis: {//y轴会自动创建数据
        },
        series: [//图表内容
          {
            name: '销售额',
            type: 'line',
            data: [120, 200, 150, 80, 70, 110, 130],,
            smooth: true,//是否平滑曲线显示
          },
          {
            name: '销售量',
            type: 'bar',
             data: [120, 200, 150, 80, 70, 110, 130],
          }

        ]
      });
    },

饼图

复制代码
 pie(){
       let myChart = echarts.init(document.getElementById('pie'));
        myChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 1048, name: 'Search Engine' },
              { value: 735, name: 'Direct' },
              { value: 580, name: 'Email' },
              { value: 484, name: 'Union Ads' },
              { value: 300, name: 'Video Ads' }
            ]
          }
        ]
      });
    },

注意的地方:created调用location事件时获取dom对象,是不行的,因为在created钩子函数中是获取不到dom的,我们可以使用mounted钩子替换成created钩子

从后端取数据

发现后端给我们返回的不是echarts的格式 ,这个时候我们做一个操作

下一步操作 遍历内容 数据格式转换

最后一步 在echarts柱状图或者折线图里边去显示这些数据

复制代码
    methods:{
        // -----获取图标动态数据
        async format(){
          let res = await this.$api.format()
          console.log('获取图标动态数据---',res.data);
          console.log(res.data.result.data.sale_money);//[{}{}]
          // 折线图 柱状图数据格式:[xx,xx,xx]
          // 获取x轴的数据名称
          let arr = res.data.result.data.sale_money;//拿到数据
          let arrx = []
          let total = []
          let money = []
          arr.forEach((ele)=>{//ele是取每一项
             arrx.push(ele.name)
             total.push(ele.num)
             money.push(ele.total_amount)
          })
             console.log(arrx);
             console.log(total);
             console.log(money);
             this.line(arrx,money,total)
        },
         //绘制图表--折线------------------
      line(arrx,money,total) {
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('charts'));
        // 绘制图表
        myChart.setOption({
          tooltip: {//提示框组件
            trigger: 'axis',
          },
          legend: {},
          toolbox: {
            feature: {
              // dataZoom: {
              //   yAxisIndex: 'none'
              // },
              // restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {//x轴数据
            data:arrx,
          },
          yAxis: {//y轴会自动创建数据
          },
          series: [//图表内容
            {
              name: '销售额',
              type: 'line',
              data:money,
              smooth: true,//是否平滑曲线显示
            },
            {
              name: '销售量',
              type: 'bar',
              data: total,
            }

          ]
        });
      },
      },

饼状图取数据 发现

数据循环遍历+数据格式转换

复制代码
    let pieData = []
          arr.forEach((ele)=>{//ele是取每一项
            //饼图--对象数据
            let obj={}
            obj.name = ele.name;
            obj.value = ele.total_amount;
            pieData.push(obj)//[{name:,value:},{},{}]
          })
             console.log('饼图',pieData);

饼图最后一步 在echarts柱状图或者折线图里边去显示这些数据

复制代码
   //绘制饼图
    pie(pieData) {
      var myChart = echarts.init(document.getElementById('pie'));
      var option;
      option = {
        tooltip: {
          trigger: 'item',
          formatter:'{a}<br/>{b}:{d}%'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '产品销售额',
            type: 'pie',
            radius: '50%',
            data:pieData,
            // data: [//[{},{}]
            //   { value: 1048, name: '审议' },
            //   { value: 735, name: '淘宝' },
            //   { value: 580, name: '京东' }
            // ],
            emphasis: {//高亮配置
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      option && myChart.setOption(option);
    },

全部代码

复制代码
<template>
  <div class="home">
    <!--1.  顶部区域布局---------- -->
    <div class="header">
      <div class="item">
        总销售额
        <div class='num'>{{ totalData.saleTotal | num}}</div>
        <div class="bottom">今日销售额:{{totalData.sale | num}}</div>
      </div>
      <div class="item">总访问量
        <div class='num'>{{ totalData.viewsTotal | num}}</div>
         <div class="bottom">今日访问量:{{totalData.views | num}}</div>
      </div>
      <div class="item">总收藏量
        <div class='num'>{{ totalData.collectTotal | num  }}</div>
         <div class="bottom">今日销售额:{{ totalData.collectTotal | num}}</div>
      </div>
      <div class="item">总支付量
        <div class='num'>{{totalData.payTotal | num }}</div>
         <div class="bottom">今日支付量:{{ totalData.pay | num}}</div>
      </div>
    </div>

      <!--2. 访问数据统计 ----------------->
      <div class="content">
      <div class="time-info" id='box13'>
        <div class="title">月销售额</div>
        <div id="charts" style="width: 100%; height: 300px"></div>
      </div>
      <div class="area" id="box1">
         <div class="title">产品销售比例</div>
        <div id="pie" style="width: 100%; height: 300px"></div>
      </div>
    </div>


    <!-- 3.  -->
     <!-- 最新内容 -->
     <div class="home-footer">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>今日订单</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="8">
             <div class="title">今日订单数</div>
              <div>{{ orderData.curOrderCount }}</div>
            </el-col>
            <el-col :span="8">
              <div class="title">汇总确认订单</div>
             <div>{{ orderData.curCollect }}</div>
            </el-col>
            <el-col :span="8">
              <div class="title">今日金额</div>
             <div>{{ orderData.curMoney }}</div>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>本月订单</span>
        </div>
        <div class="text item">
          <el-row>
            <el-col :span="8">
             <div class="title">本月订单数</div>
              <div>{{ orderData.orderCount }}</div>
            </el-col>
            <el-col :span="8">
              <div class="title">汇总确认订单</div>
             <div>{{ orderData.collect }}</div>
            </el-col>
            <el-col :span="8">
              <div class="title">本月金额</div>
             <div>{{ orderData.money }}</div>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>快捷入口</span>
        </div>
        <div class="text item">
          <el-button type="primary">产品管理</el-button>
          <el-button>消息管理</el-button>
          <el-button>内容管理</el-button>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script>
import * as echarts from 'echarts'; 
export default {
     data(){
        return{
            totalData:{},//数据统计
            orderData:{},//订单数据
        }
    },
    created(){
        this.totalInfo();//打开页面就要加载
        this.orderinfo();//
        this.format();
    },
    mounted(){//最早获取DOM元素的生命周期函数 挂载完毕
    console.log('mounted-id' , document.getElementById('charts'))
      // this.line()
      // this.pie()
    },
    methods:{
      // ------获取首页统计数据
        async totalInfo(){
            let res = await this.$api.totalInfo();
            console.log('首页统计信息---',res.data);
            this.totalData = res.data.data.list;
            // console.log( res.data.data.list);
        },
         // ----获取今日订单数据
        async orderinfo(){
          let res = await this.$api.orderinfo()
          console.log('首页统计信息---',res.data);
          this.orderData = res.data.list
        },
        // -----获取图标动态数据
        async format(){
          let res = await this.$api.format()
          console.log('获取图标动态数据---',res.data);
          console.log(res.data.result.data.sale_money);//[{}{}]
          // 折线图 柱状图数据格式:[xx,xx,xx]
          // 获取x轴的数据名称
          let arr = res.data.result.data.sale_money;//拿到数据
          let arrx = []
          let total = []
          let money = []
          let pieData = []
          arr.forEach((ele)=>{//ele是取每一项
            arrx.push(ele.name)
            total.push(ele.num)
            money.push(ele.total_amount)
            //饼图--对象数据
            let obj={}
          
            obj.name = ele.name;
            obj.value = ele.total_amount;
            pieData.push(obj)//[{name:,value:},{},{}]
          })
             console.log(arrx);
             console.log(total);
             console.log(money);
             this.line(arrx,money,total)
             this.pie(pieData)
             console.log('饼图',pieData);
        },
         //绘制图表--折线------------------
      line(arrx,money,total) {
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('charts'));
        // 绘制图表
        myChart.setOption({
          tooltip: {//提示框组件
            trigger: 'axis',
          },
          legend: {},
          toolbox: {
            feature: {
              // dataZoom: {
              //   yAxisIndex: 'none'
              // },
              // restore: {},
              saveAsImage: {}
            }
          },
          xAxis: {//x轴数据
            data:arrx,
          },
          yAxis: {//y轴会自动创建数据
          },
          series: [//图表内容
            {
              name: '销售额',
              type: 'line',
              data:money,
              smooth: true,//是否平滑曲线显示
            },
            {
              name: '销售量',
              type: 'bar',
              data: total,
            }

          ]
        });
      },
       //绘制饼图
    pie(pieData) {
      var myChart = echarts.init(document.getElementById('pie'));
      var option;
      option = {
        tooltip: {
          trigger: 'item',
          formatter:'{a}<br/>{b}:{d}%'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '产品销售额',
            type: 'pie',
            radius: '50%',
            data:pieData,
            // data: [//[{},{}]
            //   { value: 1048, name: '审议' },
            //   { value: 735, name: '淘宝' },
            //   { value: 580, name: '京东' }
            // ],
            emphasis: {//高亮配置
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      option && myChart.setOption(option);
    },
    },
    // 使用过滤器----处理数据格式
    filters:{
      num(value){
        if(!value) return;
        return value.toLocaleString();
      }
    }

}
</script>

<style lang="less" scoped>
.home {
  margin: 10px;
}
.header {
  display: flex;
  padding-right: 30px;
  .item {
    flex: 1;
    height: 100px;
    padding: 10px;
    background: #fff;
    border-radius: 10px;
    margin-left: 20px;
    margin-right: 20px;
    font-weight: bold;
    color: #fff;
    // text-align: center;
    position: relative;
    .num {
      font-size: 22px;
      margin: 10px;
      color: #fff;
    }
    .bottom {
      position: absolute;
      border-top: 1px solid rgb(246, 245, 245);
      padding: 10px 20px;
      bottom: 0;
      right: 0;
      left: 0;
      color: #fff;
      font-weight: normal;
    }
  }
  .item:nth-child(1) {
    background-image: linear-gradient(#df887d, #88554d);
  }
  .item:nth-child(2) {
    background-image: linear-gradient(#409eff, #2e556e);
  }
  .item:nth-child(3) {
    background-image: linear-gradient(#b54fa8, #713c7a);
  }
  .item:nth-child(4) {
    background-image: linear-gradient(#1cd2f1, #39717a);
  }
}
/deep/.el-card__body{
  // border: 1px solid red;
  text-align: center;
  line-height: 30px;
}
// 图表

.content {
  margin: 20px;
  display: flex;
  height: 320px;
  .time-info {
    flex: 2;
    background: #fff;
    margin-right: 20px;
    padding: 10px;
  }
  .area {
    flex: 1;
    background: #fff;
    padding: 10px;
  }
}

//内容

.home-footer {
  display: flex;
  padding-left: 20px;
  margin-bottom: 20px;
  .box-card {
    flex: 1;
    margin-right: 30px;
    span {
      font-weight: 600;
    }
  }
}

</style>
相关推荐
北城笑笑1 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅2 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
如夏倾城4 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化4 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter5 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞5 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger6 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户69371750013848 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕9 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li9 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain