柱状图带分页和自动轮播的用法

546 阅读1分钟
1.页面结构
<template>
  <div class="com-container">
    <div class="com-chart" ref="sellerRef"></div>
  </div>
</template>

2.逻辑结构

<script>
export default {
  data () {
    return {
      // 初始化的图表
      chartInstance: null,
      allDate: null, // 服务器返回的数据
      currentPage: 1, // 当前显示的页数
      totalPage: 0, // 一共有多少页
      timerId: null // 定时器标识
    }
  },
  methods: {
    // 初始化echartInstance对象
    initChart () {
      // 获取dom对象
      this.chartInstance = this.$echarts.init(this.$refs.sellerRef)
      // 对图表对象进行鼠标事件监听
      // 鼠标移入关闭定时器
      this.chartInstance.on('mouseover', () => {
        clearInterval(this.timerId)
      })
      // 鼠标离开重新启动定时器
      this.chartInstance.on('mouseout', () => {
        this.startInterval()
      })
    },
    // 获取服务器数据
    async getData () {
      const { data: res } = await this.$http.get('seller')
      this.allDate = res
      // 对数据进行从小到大排序
      this.allDate.sort((a, b) => {
        return a.value - b.value
      })
      // 每五个元素显示一页
      // 如果能数据能被5整除 数据的长度/5 = 页数 不能整除就+1
      this.totalPage = this.allDate.length % 5 === 0 ? this.allDate.length / 5 : this.allDate.length / 5 + 1
      this.updateChart()
      // 启动定时器 每隔3秒获取数据
      this.startInterval()
    },
    // 更新图表
    updateChart () {
      // 开始截取的位置
      const start = (this.currentPage - 1) * 5 // 开始是0
      const end = this.currentPage * 5 // 结束是5
      const showDate = this.allDate.slice(start, end)
      // 遍历数据提取name y轴数据
      const sellerNames = showDate.map(item => {
        return item.name
      })
      // x轴数据
      const sellerValues = showDate.map(item => {
        return item.value
      })
      const option = {
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          // y轴坐标轴使用遍历出来的name
          data: sellerNames
        },
        series: [
          {
            // 类型为柱状图
            type: 'bar',
            // x轴数据需要设置在series的data类型为遍历的value
            data: sellerValues
          }
        ]
      }
      // 渲染optio数据给dom对象
      this.chartInstance.setOption(option)
    },
    // 获取数据
    startInterval () {
      // 判断定时器是否存在
      if (this.timerId) {
        clearInterval(this.timerId)
      }
      this.timerId = setInterval(() => {
        this.currentPage++
        // 判断当前页数是否大于总页数 不加这恶判断会出现空白页
        if (this.currentPage > this.totalPage) {
          // 大于重置为1
          this.currentPage = 1
        }
        this.updateChart()
      }, 3000)
    }
  },
  // dom加载完成调用
  mounted () {
    this.initChart()
    this.getData()
  },
  destroyed () {
    clearInterval(this.timerId)
  }
}
</script>

3.要修改配置 或者需要主题配置文件可在评论区留言获取