Vue中基于Vuex使用echarts组件动态数据绑定的方法

效果如下:

在这里插入图片描述

在这里插入图片描述

1、导入echarts组件,建议使用4.9.0版本,5.0.1可能会报错

npm uninstall echarts //卸载

npm install echarts@4.9.0//引入特定组件

2、引入echarts组件,可以在main.js中引入

//报表
import echarts from 'echarts'
//Vue.use(echarts)
Vue.prototype.$echarts = echarts

3、单独把echarts的图表写出来

在这里插入图片描述

4、写echarts组件

柱状分析图

<template>
  <div ref="chart" class="container"></div>
</template>

<script>
  export default {
    data: function() {
      return {};
    },
    methods: {
      initChart() {
        let myChart = this.$echarts.init(this.$refs.chart);
        myChart.setOption({
          title: {
            text: '柱状分析图'
          },
          tooltip: {},
          xAxis: {
            type: 'category',
            data: this.keyData,
          },
          yAxis: {
            type: 'value',
          },
          series: [{
            data: this.valueData,
            type: 'bar'
          }]

        })
      }

    },
    computed: {
      keyData: function() {

        return this.$store.getters.getKeyData;

      },
      valueData: function() {
        return this.$store.getters.getValueData;
      }

    },


    mounted() {
      this.initChart();
    },

  }
</script>


<style>
  .container {
    width: 500px;
    height: 300px;
  }
</style>

饼状图
<template>
  <div ref="chart" class="container"></div>
</template>

<script>
  export default {
    data: function() {
      return {};
    },
    methods: {
      initChart() {
        let myChart = this.$echarts.init(this.$refs.chart);
        myChart.setOption({
          title: {
            text: '圆形分析图',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
          },
          series: [{
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            data: this.pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        })
      }

    },
    computed:{
      pieData:function(){
        return this.$store.getters.getPieData;
      }
    },
    mounted() {
      this.initChart();
    }
  }
</script>

<style>
  .container {
    width: 500px;
    height: 300px;
  }
</style>

5、在需要的地方引入图表组件

<template>
  <!--客户流失-->
  <div>
    <!--面包屑-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/hello' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>销售统计</el-breadcrumb-item>
    </el-breadcrumb>

    <!--按钮-->
    <div align="center" class="div-button">
      <el-button-group>
        <el-button type="primary" icon="el-icon-s-data" @click="cutColumnar">柱形分析图</el-button>
        <el-button type="success" @click="cutRound">圆形分析图 <i class="el-icon-pie-chart"></i></el-button>
      </el-button-group>
    </div>

    <!--分析图-->
    <div align="center" class="div-analysis">
      <Histogram v-show="columnar" v-if="isRouterAlive"></Histogram>
      <PieChart v-show="round" v-if="isRouterAlive"></PieChart>
      <div v-if="!isRouterAlive">
        <br>
        <br>
        <br>
        <h1>暂无数据</h1>
        <br>
        <br>
        <br>
      </div>
    </div>
    <!--表单按钮组-->
    <div align="center" class="div-button">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="日期:">
          <el-date-picker v-model="formInline.ataDate" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit(1)">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--表格-->
    <div align="center">
      <template>
        <el-table :data="tableData" height="250" border style="width: 96%">
          <el-table-column type="index" label="编号" width="250" :index="indexMethod">
          </el-table-column>
          </el-table-column>
          <el-table-column prop="tName" label="商品类型">
          </el-table-column>
          <el-table-column prop="sumPrice" label="销售额">
          </el-table-column>
        </el-table>
      </template>
      <!--分页组件-->
      <div class="div-pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[5, 10]" :page-size="rows" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

    </div>
    <router-view>
    </router-view>
  </div>
</template>

<script>
  import Histogram from '@/views/statistic/graph/Histogram.vue'
  import PieChart from '@/views/statistic/graph/PieChart.vue'

  export default {
    data: function() {
      return {
        //控住图表组件切换
        columnar: true,
        round: false,
        //
        formInline: {
          ataDate: '',
        },
        //表格
        tableData: null,
        //控制表格显示,用于刷新组件
        isRouterAlive: true,

        //分页
        page: 1,
        rows: 5,
        total: 0,
      }

    },
    components: {
      Histogram,
      PieChart
    },
    methods: {
      //表格的编号(这个编号不是在数据库查到的,而是在前端自己定义的,这样更灵活)
      indexMethod: function(index) {
        return (this.page - 1) * this.rows + (index + 1);
      },
      //切换组件
      cutColumnar: function() {
        this.columnar = true;
        this.round = false;
      },
      cutRound: function() {
        this.round = true;
        this.columnar = false;
      },
      //分页
      handleSizeChange: function(rows) {
        this.page = 1;
        this.rows = rows;
        this.query();
      },
      handleCurrentChange: function(page) {
        this.page = page;
        this.query();
      },
      //表单提交
      onSubmit: function(page) {
        //页码跳转第一页
        this.page = page;
        //查询
        this.query();
      },
      //查询
      query: function() {
        //跳转路径
        let url = this.axios.urls.STATISTIC_QUERYSALES;
        //参数
        if(this.formInline.ataDate==null){
          //日期组件如果不加判断,在清空再查的时候会报错
          this.formInline.ataDate="";
        }

        let primarys = {
          startTime: this.formInline.ataDate[0],
          endTime: this.formInline.ataDate[1],
          page: this.page,
          rows: this.rows,
        }

        this.axios.post(url, primarys).then(resp => {
          //ajax返回的数据
          let json = resp.data;
          //判断是否请求成功 这个基于后台的响应封装类
          if (json.status == 200) {
            //后台返回的表格数据
            let arr = json.data;
            //把数据绑定在数据表格上
            this.tableData = arr;
            /*
                        柱状图需要的数据格式是这样的:
                        option = {
                          xAxis: {
                            type: 'category',
                            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
                          },
                          yAxis: {
                            type: 'value'
                          },
                          series: [{
                            data: [120, 200, 150, 80, 70, 110, 130],
                            type: 'bar'
                          }]
                        };

                        饼状图是这样的: {
                          value: 535,
                          name: '荆州'
                        }, {
                          value: 510,
                          name: '兖州'
                        }, {
                          value: 634,
                          name: '益州'
                        }, {
                          value: 735,
                          name: '西凉'
                        }

                        */
            //我们需要把数据格式转换成想要的效果(当然也可以查出来就是符合的格式)

            //柱状图需要的数据格式
            let keyData = [];
            let valueData = [];
            //饼图需要的数据格式
            let pieData = [];

            //数据转换
            for (let i = 0; i < arr.length; i++) {
              keyData.push(arr[i].tName);
              valueData.push(arr[i].sumPrice);

              pieData.push({
                value: arr[i].sumPrice,
                name: arr[i].tName
              });
            }

            //放入vuex中

            //柱状图所需要的数据
            this.$store.commit('setKeyData', {
              keyData: keyData,
            });
            this.$store.commit('setValueData', {
              valueData: valueData,
            });
            //饼状图所需要的数据
            this.$store.commit('setPieData', {
              pieData: pieData,
            });

          } else {
            this.tableData = null;
          }

        })

      }
    },
    watch: {
      //监听表格,当表格数据发生变化就要引起统计图的值改变
      tableData(searchWord, retWord) {
        //当表格没有值的时候显示"暂无数据"
        if (searchWord == null) {
          this.isRouterAlive = false
        } else {
          //当表格刷新且有值就刷新这图表
          this.isRouterAlive = false
          // //this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行
          this.$nextTick(() => (this.isRouterAlive = true))
        }


      }

    },
    created: function() {
      this.query();
    }

  }
</script>

以上给大家一个动态实现统计报表的思路,这样做的好处是一个图表可以用在多个页面中,只需要做参数上的处理就可以,其他的图表可以依照这个思路参考

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值