基于APEXCHARTS图表组件简单封装,vue页面使用时代码更优化

封装界面

myChart.vue

<template>
  <vue-apex-charts :height="currentHeight" :options="chartOptions" :series="series" ></vue-apex-charts>
</template>
<script>
import VueApexCharts from "vue-apexcharts"
let timerId = null
  export default {
  name: 'myCharts',
  props: ['title', 'type', 'interval', 'url', 'config', 'width', 'height', 'params'],
    data() {
      return {
        currentHeight: this.height ? this.height : '350px',
        seriesList: [],
        selectedList: [],
        series: [],
        chartOptions: {
          chart: {
            type: 'line'
          },
          dataLabels: {
            enabled: false
          },
          title: {
            text: '',
            align: 'left'
          },
          grid: {
            borderColor: '#cdcdcd',
            width: 1,
            strokeDashArray: 2
          },
          plotOptions: {
            bar: {
            }
          },
          legend: {
            show: true,
            position: 'bottom', // 小圆点显示的位置,默认是bottom
            width: 'auto',
            markers: {
              radius: 12
            }
          },
          stroke: {
          },
          gradient: {
            shadeIntensity: 0.9,
            opacityFrom: 0.7,
            opacityTo: 0.5,
            stops: [0, 80, 100]
          },
          fill: {
          },
          xaxis: {
            categories: []
          },
          yAxis: {
            tickAmount: 5
          },
          tooltip: {
            x: { show: true }
          }
        }
      }
    },
    methods: {
      // 设置title和title显示
      setTitle() {
        if (this.title) {
          this.chartOptions.title.text = this.title.text ? this.title.text : this.title
          if (this.title.align) {
              this.chartOptions.title.align = this.title.align
          }
        }
      },
      // 设置类型
      setType() {
        this.chartOptions.chart.type = this.type
          // 加载完了type在加载对应的配置文件
          switch (this.type) {
            case 'line':
              this.setLineConfig()
              break;
            case 'bar':
              this.setBarConfig()
              break;
            case 'area':
              break;
          
            default:
              break;
          }
      },
      // 设置line的特有配置文件
      setLineConfig() {
        if (this.config) {
          if (this.config.smooth) {
            this.chartOptions.stroke.curve = 'smooth'
          }
        }
      },
      // 设置bar的特有配置文件
      setBarConfig() {
        if (this.config) {
          if (this.config.horizontal) {
            this.chartOptions.plotOptions.bar.horizontal = true
          }
          if (this.config.fill) {
            this.chartOptions.fill = this.config.fill
          }
        }
      },
      // 设置url
      setUrl() {
        if (this.url.constructor === Array) {
          // 1.  :url="urlData",其中urlData的初始化为[]  --> 直接把这个值赋值给this.series
          this.series = this.$parent.getChartData()
        } else {
          // 2. :url="'/demo/charts/configLinebar'"    -->  底层调用接口获取数据,再赋值给this.series
          const getAllMetaTable = (params) => axios.get(prefix + '/jdts/getMetaTransportMapConfig', { params }).then(res=>{return res.info})
        }
      },
      // 设置通用参数
      setCommon() {
        if (this.config) {
          if (this.config.position) { // 设置legend,即小圆点显示的位置
            this.chartOptions.legend.position = this.config.position
          }
          if (!this.config.toolbar.show) { // 设置右上角默认的图标是否显示
            this.chartOptions.chart.toolbar = this.config.toolbar
          }
          if (this.config.categories) { // 设置x轴显示
            this.chartOptions.xaxis.categories = this.config.categories
          }
        }
      },
      // 后台请求接口,这里直接获取后台数据
      getData() {
        // console.log('获取数据')
        // let series = []
        // for (let i = 0; i < 2; i++) {
        //   let obj = {
        //     name: 'series' + i,
        //     data: []
        //   }
        //   for (let j = 0; j < 7; j++) {
        //     const newData1 = Math.floor(Math.random() * 100)
        //     obj.data.push(newData1)
        //   }
        //   series.push(obj)
        // }
        // return series
      },
      init() {
        let _this = this
        this.setTitle()
        this.setCommon()
        this.setType()
        this.setUrl() // 相当于初始化图
        if (_this.interval > 0) {
          timerId = setInterval(() => {
            _this.updateChart()
          }, 1000 * _this.interval);
        }
      },
      updateChart() {
        // 这里应该调csLine中的getData()函数,获取最新的urlData
        // this.series = this.$parent.getChartData()
        this.setUrl()
      }
    },
    created() {
      this.init()
    },
    // watch: {
    //   url: {
    //     handler (val) {
    //       console.log(val)
    //       // this.drawCrudGraph(val)
    //     }
    //   },
    //   deep: true
    // },
    // mounted () {
    //   this.setUrl()
    // },
    components: {
      VueApexCharts
    },
    beforeDestroy () {
      if (timerId) {
        clearInterval(timerId)
        timerId = null
      }
    }
  }
</script>

csLine.vue

<template>
    <myCharts 
    :type="type"
    :interval="time"
    :url="urlData"
    :title="title"
    :config="config"
    :height="height"
    ></myCharts>
</template>
<script>
import myCharts from './myCharts'
    export default {
      data() {
        return {
          title: {
            text: '折线图',
            align: 'center' // 默认是左边显示
          }, // 选填;
          type: 'bar', // 必填; 图表类型:line、area、bar、radar等
          time: 6, // 必填;
          config: { // 放一些对应的配置文件
            smooth: false, // 是否为光滑的曲线
            // horizontal: false, // 是否水平
            toolbar: { show: false }, // 是否显示右上角默认的图标按钮
            categories: [],
            // fill: {
            //   colors: ['#F45DAA'],
            //   type: 'gradient', // 梯度
            //   gradient: {
            //     type: 'horizontal', // 水平方向的梯度
            //     gradientToColors: ['#FDAED1'], // 渐变结束的颜色
            //     opacityFrom: 1, // 透明度
            //     opacityTo: 1,
            //     stops: [0, 120]
            //   }
            // },// 设置填充颜色, 这个只适用于单个数据的bar
            // position: 'top' // legend显示的位置,默认是bottom
          }, // 选填
          height: '350px', // 选填; 默认高度是350px
          /**
           * urlData写的有两种:
           *    1. :url="'/demo/charts/configLinebar'"    --> 一般这种情况很少,因为页面还要传对应的请求参数下去
           *    2. :url="urlData",其中urlData的初始化为[]   --> 大多数还是这种情况,页面直接调接口,传对应的数据
           */
          // urlData: 'demo/list',
          urlData: [],
          params: {}, // 当:url="'/demo/charts/configLinebar'"为这种格式时,请求接口的参数放在这个对象中。
        }
      },
      components: {
        myCharts
      },
      methods: {
        getChartData () { // 获取数据的接口函数,请用getData()
          let series = []
          for (let i = 0; i < 3; i++) {
            let obj = {
              name: 'series' + i,
              data: []
            }
            for (let j = 0; j < 7; j++) {
              const newData1 = Math.floor(Math.random() * 100)
              obj.data.push(newData1)
            }
            series.push(obj)
          }
          this.urlData = series
          // 在请求接口的时候,设置categories
          // this.config.categories = [7, 6, 5, 4, 3, 2, 1]
          return series
        }
      },
      created() {
        this.getChartData()
      }
    };
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值