<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)
}
}
}
效果