echart柱状图无缝轮播 vue3.2

效果图

 

 

 代码:

 

<template>
  <div class="home">
    <div ref="myRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
// import Echarts from '@/utils/echarts'
import * as Echarts from 'echarts'
/**
 * 数据
 */
const myRef = ref(null)
let timer = null

/**
 * 生命周期
 */
onMounted(() => {
  barChart()
})
onBeforeUnmount(() => {
  _clearInterval(timer)
})

/**
 * 函数
 */
function barChart () {
  const chartInstance = myRef.value && Echarts.init(myRef.value)
  // 控制显示几个柱子
  const [startValue, endValue] = [0, 3]
  // 数据
  const data = [
    { name: 'Mon', vaule: 120 },
    { name: 'Tue', vaule: 200 },
    { name: 'Wed', vaule: 150 },
    { name: 'Thu', vaule: 80 },
    { name: 'Fri', vaule: 40 },
    { name: 'Sat', vaule: 110 },
    { name: 'Sun', vaule: 120 }
  ]

  const xAxisData = data.map(item => item.name)
  const seriesData = data.map(item => item.vaule)

  const option = {
    title: [
      {
        text: ' 数据统计',
        left: '3%',
        textStyle: {
          fontSize: 30,
          color: '#333',
          height: 40,
          width: 40,
          lineHeight: 40
        }
      }
    ],
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    // 控制显示几个柱子
    dataZoom: {
      show: false,
      startValue,
      endValue
    },
    yAxis: {
      type: 'value'
    },
    series: {
      data: seriesData,
      type: 'bar'
    }
  }
  chartInstance.setOption(option)

  // 使用定时器
  timer = setInterval(() => {
    const item1 = xAxisData.shift()
    xAxisData.push(item1)
    const item2 = seriesData.shift()
    seriesData.push(item2)
    chartInstance.setOption({
      series: {
        data: seriesData,
        type: 'bar'
      },
      xAxis: {
        type: 'category',
        data: xAxisData
      }
    })
  }, 2000)
}

/**
 * @param timeId {Number}
 */
function _clearInterval (timeId) {
  timeId && window.clearInterval(timeId)
}
</script>
<style scoped>
.home > div {
  height: 500px;
  width: 800px;
}
</style>

 

结语 : 只是拿柱状图示范 其他图形如果有轮播的需求也可以用类似方法 如果有更好的方法可以在评论区告诉我 非常感谢

posted @ 2021-12-28 16:38  祁腾飞  阅读(1659)  评论(0编辑  收藏  举报