vue父子传值 echarts图的应用

文章展示了如何在Vue.js应用中利用Echarts库创建条形图、圆形图和饼图。代码详细解释了从接口获取数据、初始化图表、设置图表选项以及处理数据更新的过程。涉及到的图表元素包括线条样式、阴影、网格、坐标轴、数据标签和动画效果。
摘要由CSDN通过智能技术生成

实现的效果图

 条线图

代码解析

 接口取值

 渲染

    initChart() {
      if (this.$refs.lineCharts) {
        //echarts销毁实例
        echarts.dispose(this.$refs.lineCharts)
      }
      this.chart = echarts.init(this.$refs.lineCharts)
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器,坐标轴触发有效
            type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
          }
        },
        grid: {
          top: 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: this.days,   //获得x轴得数据
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '发送总量',
          type: 'line',
          stack: 'vistors',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 1, color: '#188df0' }
            ])
          },
          data: this.smsNum,    //获得y轴得数据
          animationDuration: 2000
        }]
      }
      this.chart.setOption(option)
    },

圆型图

<template>
  <div :class="className" :style="{height:height,width:width}">
    <div ref="ringCharts" style="width: 100%;height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {selectSmsApiStatusVOList} from "@/api/message";

const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    apiCode: '',
    required: true,
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      MapList: [],
      nameData: [],
      toBeSend: [],
      sending: [],
      sendSuccess: [],
      sendFailed: [],
      days: [],
      newApiCode: "",
      chart: null,
    }
  },
  created() {
    this.newApiCode = this.apiCode
    this.getLineList()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  watch: {
// 因为在vue生命周期中子组件创建后只会赋一次值,之后父组件数值变化了,
//  子组件的数值也会变化,但显示的数据不会发生改变。
//  所以需要监听父组件传参变化重新赋值让子组件重新赋值。
//  此处的isShow并不是函数,而是对应的要赋值的变量名isShow
    apiCode(val) {
      this.newApiCode = val
      this.getLineList()
    }
  },

  methods: {
    getLineList() {
      selectSmsApiStatusVOList(this.newApiCode).then(response => {
        this.MapList = response.data
        let MapList = this.MapList;
        if (MapList && MapList.length !== 0) {
          let obj = eval(MapList);
          for (let i = 0; i < obj.length; i++) {
            this.toBeSend.push(obj[i].toBeSend);
            this.sending.push(obj[i].sending);
            this.sendSuccess.push(obj[i].sendSuccess);
            this.sendFailed.push(obj[i].sendFailed);
          }
        } else {
          this.toBeSend = []
          this.sending = []
          this.sendSuccess = []
          this.sendFailed = []
        }
        this.$nextTick(() => {
          this.initChart()
        })
      });
    },
    initChart() {
      if (this.$refs.ringCharts) {
        //echarts销毁实例
        echarts.dispose(this.$refs.ringCharts)
      }
      this.chart = echarts.init(this.$refs.ringCharts)
      let option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '短信状态占比图',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: 'bold',
                formatter: `{b} \n {d}%`     //此处的7为假数据,其实就是下面data数组中的value相加,都可以取到的,但是此处都是模拟数据
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: this.toBeSend, name: '待发送'},
              {value: this.sending, name: '发送中'},
              {value: this.sendSuccess, name: '发送成功'},
              {value: this.sendFailed, name: '发送失败'}
            ]
            // data: [
            //   { value: 1048, name: 'Search Engine' },
            //   { value: 735, name: 'Direct' },
            //   { value: 580, name: 'Email' },
            //   { value: 484, name: 'Union Ads' },
            //   { value: 300, name: 'Video Ads' }
            // ]
          }
        ]
      }
      this.chart.setOption(option)
    },
  }
}
</script>

条形图

<template>
  <div :class="className" :style="{height:height,width:width}">
    <div ref="barCharts" style="width: 100%;height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {selectSmsApiStatusVOList, selectSmsApiTypeVOList} from "@/api/message";

const animationDuration = 3000

export default {
  mixins: [resize],
  props: {
    apiCode: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      MapList: [],
      smsNum: [],
      toBeSend: [],
      sending: [],
      sendSuccess: [],
      sendFailed: [],
      nameData: [],
      text: [],
      totalData: [],
      newApiCode: "",
    }
  },
  created() {
    this.newApiCode = this.apiCode
    this.getBarList()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  watch: {
// 因为在vue生命周期中子组件创建后只会赋一次值,之后父组件数值变化了,
//  子组件的数值也会变化,但显示的数据不会发生改变。
//  所以需要监听父组件传参变化重新赋值让子组件重新赋值。
//  此处的isShow并不是函数,而是对应的要赋值的变量名isShow
    apiCode(val) {
      this.newApiCode = val
      this.getBarList()
    }
  },
  methods: {
    getBarList() {
      selectSmsApiTypeVOList(this.newApiCode).then(response => {
        this.MapList = response.data
        let MapList = this.MapList;
        if (MapList && MapList.length !== 0) {
          let obj = eval(MapList);
          for (let i = 0; i < obj.length; i++) {
            this.nameData.push(obj[i].smsType.text);
            this.totalData.push(obj[i].smsNum)
          }

        } else {
          this.nameData = []
          this.totalData = []
        }
        this.$nextTick(() => {
          this.initChart()
        })
      });
    },
    initChart() {
      if (this.$refs.barCharts) {
        //echarts销毁实例
        echarts.dispose(this.$refs.barCharts)
      }
      this.chart = echarts.init(this.$refs.barCharts)

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // Use axis to trigger tooltip
            type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
          }
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: this.nameData
        },
        series: [
          {
            name: '短信总量(单位:条)',
            type: 'bar',
            stack: 'total',
            showBackground: true,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                // { offset: 0, color: '#83bff6' },
                // { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            color: '',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: this.totalData
          }
        ]
      })
    }
  }
}
</script>

饼图 

<template>
  <div :class="className" :style="{height:height,width:width}">
    <div ref="pieCharts" style="width: 100%;height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {selectSmsApiAppVOList} from "@/api/message";

export default {
  mixins: [resize],
  props: {
    apiCode:{
      type: String,
      required: true,
    },

    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      MapList: [],
      rows: [],
      newApiCode: "",
      PieValue: '',
      PieName: '',
      nameData: [],
      totalData: []
    }
  },
  created() {
    this.newApiCode = this.apiCode
    this.getPieListData()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  watch: {
// 因为在vue生命周期中子组件创建后只会赋一次值,之后父组件数值变化了,
//  子组件的数值也会变化,但显示的数据不会发生改变。
//  所以需要监听父组件传参变化重新赋值让子组件重新赋值。
//  此处的isShow并不是函数,而是对应的要赋值的变量名isShow
    apiCode(val) {
      this.newApiCode = val
      this.getPieListData()
    }
  },
  methods: {
    getPieListData() {
      this.loading = true;
      selectSmsApiAppVOList(this.newApiCode).then(response => {
        this.MapList = response.data;

        if (this.MapList && this.MapList.length !== 0) {
          let obj = eval(this.MapList);
          for (let i = 0; i < obj.length; i++) {
            this.nameData.push(obj[i].sign.text);
            this.totalData.push({value: obj[i].smsNum, name: obj[i].sign.text})
          }
        }else {
          this.nameData = []
          this.totalData = []
        }
        this.$nextTick(() => {
          this.initChart()
        })
      });
    },

      initChart() {
        if (this.$refs.pieCharts) {
          //echarts销毁实例
          echarts.dispose(this.$refs.pieCharts)
        }
        this.chart = echarts.init(this.$refs.pieCharts)

      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          show: true,
          left: 'center',
          bottom: '10',
           //data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts']
          data: this.nameData
        },
        series: [
          {
            name: '发送总量',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            // data: [
            //   { value: 320, name: 'Industries' },
            //   { value: 240, name: 'Technology' },
            //   { value: 149, name: 'Forex' },
            //   { value: 100, name: 'Gold' },
            //   { value: 59, name: 'Forecasts' }
            // ],
            data: this.totalData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值