1. 程式人生 > 實用技巧 >vue + echarts 動態折線圖(每秒重新整理)

vue + echarts 動態折線圖(每秒重新整理)

效果展示:

<div class="nowEcharts" id="nowEcharts"></div>



<style >
.nowEcharts {
  width: 100%;
  height: 300px;
  margin-bottom: 0.3rem;
}
</style>

1.先在data中定義option

nowOptions: {
        visualMap: [
          {
            show: false,
            type: 'continuous',
            seriesIndex: 
0, min: 0, max: 400, }, ], title: { left: 'left', text: '電量消耗實時統計', }, tooltip: { trigger: 'axis', formatter: function(params) { params = params[0] var date = new Date(params.name)
return ( date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1] ) }, axisPointer: { animation: false, }, }, grid: { top:
'15%', bottom: '10%', }, xAxis: { type: 'time', splitLine: { show: false, }, triggerEvent: true, }, yAxis: { type: 'value', boundaryGap: [0, '100%'], max: 100, splitLine: { show: false, }, }, series: [ { type: 'line', showSymbol: false, hoverAnimation: false, data: [], }, ], },

2.生成折線圖

(1)初始化資料

nowChart() {
      let that = this
      var data = []
      var now = +new Date()
      var value = Math.random() * 1000
      for (var i = 0; i < 60; i++) {
        now = new Date(+now + this.oneDay)
        data.push(this.randomData(now, value))
      }
      // 基於準備好的dom,初始化echarts例項
      var myChart = echarts.init(document.getElementById('nowEcharts'))

      // 繪製圖表
      var temp = 59
      let options = Object.assign(that.nowOptions, {})
      options.series.forEach((item) => {
        item.data = data
        item.markPoint = {
          data: [
            [
              {
                symbol: 'none',
                x: '95%',
              },
              {
                symbol: 'circle',
                name: '實時資料',
                value: data[temp].value[1],
                xAxis: data[temp].value[0],
              },
            ],
          ],
        }
      })
      myChart.setOption(options)
      // 1秒定時器
      setInterval(() => {
        for (var i = 0; i < 1; i++) {
          data.shift()
          now = new Date(+now + this.oneDay)
          data.push(this.randomData(now, value))
        }
        myChart.setOption(options)
      }, 1000)
    },

(2)生成隨機數

 randomData(now, value) {
      value = Math.random() * 100
      var valueName =
        now.getFullYear() +
        '/' +
        (now.getMonth() + 1) +
        '/' +
        now.getDate() +
        ' ' +
        (now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()) +
        ':' +
        (now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes()) +
        ':' +
        (now.getSeconds() >= 10 ? now.getSeconds() : '0' + now.getSeconds())
      return {
        name: now.toString(),
        value: [valueName, Math.round(value)],
      }
    },