轮询更新折线图数据

<button type="error" @click="stopTimer()">StopTimer</button>
<div id="echarts" style="height:600px;" ></div>

引入echarts插件

import * as echarts from 'echarts'
data(){
    return{
      xlist:[],
      ylist:[],
      timer:null,
      option:{}
    }
  },
  mounted() {
    // 根据窗口大小调整echarts图表
    window.onresize = () => {
      // 基于准备好的dom,初始化echarts实例
      const myChart = echarts.init(document.getElementById('echarts'))
      myChart.resize()
    }
    this.getChart()
    this.setTimer(0)
  },
  beforeUnmount() {
    window.onresize = null
    if (this.timer) {
    clearTimeout(this.timer)
  }
  },
  methods:{
    getChart(){
      const myChart = echarts.init(document.getElementById('echarts'))
      this.option={
        title: {
          text: '轮询demo'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['00:00', '01:15', '02:30', '03:45', '05:00', '06:15', '07:30', '08:45', '10:00', '11:15', '12:30', '13:45', '15:00', '16:15', '17:30', '18:45', '20:00', '21:15', '22:30', '23:45']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} W'
          },
          axisPointer: {
            snap: true
          }
        },
        series: [
          {
            name: 'Electricity',
            type: 'line',
            smooth: true,
            data: []//[300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
          }
        ]
      }
      myChart.setOption(this.option)
    },
    // 轮询方法
    setTimer(time) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.getTime()
        const myChart = echarts.init(document.getElementById('echarts'))
        this.option.xAxis.data=this.xlist
        this.option.series[0].data=this.ylist
        myChart.setOption(this.option)
      }, time)
    },
    getTime(){
      const nowdate=new Date()
      const date={
        hour:nowdate.getHours(),
        minute:nowdate.getMinutes()< 10 ? '0' + nowdate.getMinutes() : nowdate.getMinutes(),
        second:nowdate.getSeconds()< 10 ? '0' + nowdate.getSeconds() : nowdate.getSeconds()
      }
      const time = date.hour+':'+date.minute+':'+date.second
      console.log(time)
      this.xlist.push(time)
      this.ylist.push(date.second)
      this.setTimer(2000)
    },
    stopTimer(){
      if (this.timer) {
        clearTimeout(this.timer)
      }
    }
  }

效果
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值