zoukankan      html  css  js  c++  java
  • Vue笔记:封装Echarts

    Echart.vue组件的封装

    data中是固定属性,props中定义动态参数,是父组件获取数据时传递到子组件的参数,xData为横坐标轴数据,series为Echarts的series数据,isAxisChart为是否带有坐标轴。

    <template>
      <div style="height: 100%" ref="echart">
        echart
      </div>
    </template>
    
    <script>
    import echarts from 'echarts'
    export default {
      props: {
        chartData: {
          type: Object,
          default() {
            return {
              xData: [],
              series: []
            }
          }
        },
        isAxisChart: {
          type: Boolean,
          default: true
        }
      },
      computed: {
        options() {
          return this.isAxisChart ? this.axisOption : this.normalOption
        },
        isCollapse() {
          return this.$store.state.tab.isCollapse
        }
      },
      watch: {
        chartData: {
          handler: function() {
            this.initChart()
          },
          deep: true
        },
        isCollapse() {
          setTimeout(() => {
            this.resizeChart()
          }, 300)
        }
      },
      data() {
        return {
          echart: null,
          axisOption: {
            legend: {
              textStyle: {
                color: '#333'
              }
            },
            grid: {
              left: '20%'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: [],
              axisLine: {
                lineStyle: {
                  color: '#17b3a3'
                }
              },
              axisLabel: {
                color: '#333'
              }
            },
            yAxis: [
              {
                type: 'value',
                axisLine: {
                  lineStyle: {
                    color: '#17b3a3'
                  }
                }
              }
            ],
            color: [
              '#2ec7c9',
              '#b6a2de',
              '#5ab1ef',
              '#ffb980',
              '#d87a80',
              '#8d98b3',
              '#e5cf0d',
              '#97b552',
              '#95706d',
              '#dc69aa',
              '#07a2a4',
              '#9a7fd1',
              '#588dd5',
              '#f5994e',
              '#c05050',
              '#59678c',
              '#c9ab00',
              '#7eb00a',
              '#6f5553',
              '#c14089'
            ],
            series: []
          },
          normalOption: {
            tooltip: {
              trigger: 'item'
            },
            color: ['#0f78f4', '#dd536b', '#9462e5', '#a6a6a6', '#e1bb22', '#39c362', '#3ed1cf'],
            series: []
          }
        }
      },
      methods: {
        initChart() {
          this.initChartData()
          if (this.echart) {
            this.echart.setOption(this.options)
          } else {
            this.echart = echarts.init(this.$refs.echart)
            this.echart.setOption(this.options)
          }
        },
        initChartData() {
          if (this.isAxisChart) {
            this.axisOption.xAxis.data = this.chartData.xData
            this.axisOption.series = this.chartData.series
          } else {
            this.normalOption.series = this.chartData.series
          }
        },
        resizeChart() {
          this.echart ? this.echart.resize() : ''
        }
      },
      mounted() {
        window.addEventListener('resize', this.resizeChart)
      },
      destroyed() {
        window.removeEventListener('resize', this.resizeChart)
      }
    }
    </script>
    
    <style lang="scss" scoped></style>

    简单饼状图

    <template>
        <div>
            <echart :chartData="echartData.video" style="height: 260px" :isAxisChart="false"></echart>
        </div>
    </template>
    
    <script>
        import Echart from '../../components/Echart.vue';
        import axis from "axios";
        export default {
            components: {
                Echart
            },
            data() {
                return {
                    msg: '我是一个头部组件',
                    echartData: {
                        video: {
                            series: []
                        }
                    }
                }
            },
            methods: {
                getTableData() {
                    axis.get('/api/chartdata1/')//axis后面的.get可以省略;
                        .then((res) => {
                                res = res.data
                                // 视频饼图
                                this.echartData.video.series.push({
                                    data: res.data.videoData,
                                    type: 'pie'
                                })
                            })
                        .catch(
                            (error) => {
                                console.log(error);
                            });
                },
            },
            created() {
                this.getTableData()
            }
        }
    </script>
    <style lang="scss" scoped>
    
    </style>

     flask接口构造数据:

    # 获取图表数据
    # http://127.0.0.1:8081/api/chartdata1/
    @app.route('/api/chartdata1/')
    def chartdata1():
        returnres = {"state": 200, "msg": "succsuful", "data": ""}
        reslist = [{'name':'springboot','value':1000},{'name':'vue','value':800}]
        resdict = {'videoData': reslist}
        returnres["data"] = resdict
        return jsonify(returnres)

     柱状图

    <template>
        <div>
            <echart :chartData="echartData.user" style="height: 260px"></echart>
        </div>
    </template>
    
    <script>
        import Echart from '../../components/Echart.vue';
        import axis from "axios";
        export default {
            components: {
                Echart
            },
            data() {
                return {
                    msg: '我是一个头部组件',
                    echartData: {
                        user: {
                            xData: [],
                            series: []
                        },
                    }
                }
            },
            methods: {
                getTableData() {
                    axis.get('/api/chartdata2/')//axis后面的.get可以省略;
                        .then((res) => {
                                res = res.data
                                // 用户柱状图
                                // 坐标轴初始化
                                this.echartData.user.xData = res.data.userData.map(item => item.date)
                                //数据组
                                this.echartData.user.series.push({
                                    name: '新增用户',
                                    data: res.data.userData.map(item => item.new),
                                    type: 'bar'
                                })
                                this.echartData.user.series.push({
                                    name: '活跃用户',
                                    data: res.data.userData.map(item => item.active),
                                    type: 'bar',
                                    barGap: 0
                                })
                            })
                        .catch(
                            (error) => {
                                console.log(error);
                            });
                },
            },
            created() {
                this.getTableData()
            }
        }
    </script>
    <style lang="scss" scoped>
    
    </style>

    flask构造接口数据:

    # 获取图表数据
    # http://127.0.0.1:80821/api/chartdata2/?xx=
    @app.route('/api/chartdata2/')
    def chartdata2():
        returnres = {"state": 200, "msg": "succsuful", "data": ""}
        reslist = [{'date': '周一', 'new': 100, 'active': 200}, {'date': '周二', 'new': 100, 'active': 200},
                   {'date': '周三', 'new': 100, 'active': 200}, {'date': '周四', 'new': 100, 'active': 200},
                   {'date': '周五', 'new': 100, 'active': 200}, {'date': '周六', 'new': 100, 'active': 200},
                   {'date': '周日', 'new': 100, 'active': 200}]
        resdict = {'userData': reslist}
        returnres["data"] = resdict
        return jsonify(returnres)

    折线图

    <template>
        <div>
            <echart :chartData="echartData.order" style="height: 260px" ></echart>
        </div>
    </template>
    
    <script>
        import Echart from '../../components/Echart.vue';
        import axis from "axios";
        export default {
            components: {
                Echart
            },
            data() {
                return {
                    msg: '我是一个头部组件',
                    echartData: {
                        order: {
                            xData: [],
                            series: []
                        },
                    }
                }
            },
            methods: {
                getTableData() {
                    axis.get('/api/chartdata3/')//axis后面的.get可以省略;
                        .then((res) => {
                                res = res.data
                                 // 订单折线图
                                const order = res.data.orderData
                                this.echartData.order.xData = order.date
                                // 第一步取出series中的name部分——键名
                                let keyArray = Object.keys(order.data[0])
                                // 第二步,循环添加数据
                                keyArray.forEach(key => {
                                    this.echartData.order.series.push({
                                        name: key,
                                        data: order.data.map(item => item[key]),
                                        type: 'line'
                                    })
                                })
                            })
                        .catch(
                            (error) => {
                                console.log(error);
                            });
                },
            },
            created() {
                this.getTableData()
            }
        }
    </script>
    <style lang="scss" scoped>
    
    </style>

    flask接口构造数据:

    # 获取图表数据
    # http://127.0.0.1:80821/api/chartdata3/?xx=
    @app.route('/api/chartdata3/')
    def chartdata3():
        returnres = {"state": 200, "msg": "succsuful", "data": ""}
        datalist = []
        reslist = {'date':['20191001', '20191002', '20191003', '20191004', '20191005', '20191006', '20191007'],'data':''}
        for i in range(0,7):
          datalist.append(
              {
              'vue': random.randint(1, 500),
              'wechat': random.randint(1, 500),
              'ES6': random.randint(1, 500),
              'Redis': random.randint(1, 500),
              'React': random.randint(1, 500),
              'springboot': random.randint(1, 500)
            })
        reslist['data'] =datalist
        resdict = {'orderData': reslist}
        returnres["data"] = resdict
    
        return jsonify(returnres)

  • 相关阅读:
    2.1.1 Speed Limit
    2.1.2 骑自行车的最短时间
    1.3.1提高实数精度的范例
    1.2.2一个数可以有多少种用连续素数之和表示
    求二倍关系的个数 1.2.1
    求平均值
    原生JS 购物车及购物页面的cookie使用
    基于Jquery的商城商品图片的放大镜效果(非组件)
    商城商品购买数量增减的完美JS效果
    弹性布局各种坑爹兼容
  • 原文地址:https://www.cnblogs.com/-wenli/p/13936263.html
Copyright © 2011-2022 走看看