效果
先上效果图
时间轴是0-24小时的排列,内容点是传过来的数据,有数据的显示上去,并自动连成一条线
多条数据
多条数据图表:juejin.cn/post/684490…
代码
<template>
<div class="echarts-time-container">
<div class="my-echarts" ref="myEcharts"></div>
</div>
</template>
<script>
// echarts
let echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/line')
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
export default {
mounted(){
window.addEventListener("resize", this.resizeCharts);
this.$once("hook:beforeDestroy", () => {
window.removeEventListener("resize", this.resizeCharts);
});
this.getEcharts()
},
methods:{
resizeCharts(){
if(this.$refs.myEcharts){
echarts.init(this.$refs.myEcharts).resize();
}
},
getEcharts(){
let myCharts = echarts.init(this.$refs.myEcharts)
let today = this.getNowFormatDate()
let xDate = []
let contentData = []
let timeShow = ''
// 有值的数据(模拟数据,时间格式必须和x轴的格式一致)
let xChartData = [`${today} 00:00:00`,`${today} 01:45:33`,`${today} 03:05:00`,`${today} 16:10:33`,`${today} 20:01:00`]
let yChartData = [1,2,3.4,5,6]
// x轴坐标——年月日时必须的
for(var ii=0;ii<25;ii++){
timeShow = `${today} ${ii>10?ii:('0'+ii)}:00:00`
contentData.push([timeShow,''])
xDate.push(timeShow)
}
// 添加x轴数据
yChartData.map((res,index)=>{
contentData.push([xChartData[index],res])
})
myCharts.setOption({
tooltip: {
trigger: 'axis',
formatter:(val)=>{
let text = ''
val.map((res,index)=>{
text = `${res.data[0]}<br/>数值:`
if(res.data[1] === 0 || res.data[1]){
text += `${res.data[1]}`
}else{
text += '暂无数据'
}
})
return text
},
textStyle:{
align:'center'
}
},
grid: {
left: '3%',
right: '10%',
bottom: '3%',
top: '8%',
containLabel: true
},
xAxis: {
type: 'time',
boundaryGap: false,
interval:1000*3600, // 可设置显示间隔
data: xDate,
min:`${today} 0:00:00`,
},
yAxis: {
type: 'value',
max:function (value) {
if(value.max>0){
return parseInt(value.max)
}
else{
return 5;
}
},
min:0
},
series:[{
name: '',
stack:'',
type: 'line',
smooth: true,
symbol: 'circle',
symbolSize: 10,
lineStyle: {
normal: {
width: 1
}
},
data: contentData,
}]
});
},
// 获得今天时间
getNowFormatDate() {
var date = new Date();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + '-' + month + '-' + strDate
return currentdate;
}
}
}
</script>
<style lang="less">
.echarts-time-container{
.my-echarts{
width:1000px;
height: 400px;
}
}
</style>