vue中使用动态echart图表

时间:2021-12-14 03:44:02
<template>
<div class="block">
<div class="title">展会实时人流里统计</div>
<div :class="className" :id="id" :style="{height:height,width:width}"></div>
</div>
</template>
<script>
import echarts from 'echarts';

export default {
props: {
className: {
type: String,
default: 'dynamic myEchart'
},
id: {
type: String,
default: 'dynamic'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '400px'
}
},
data() {
return {
chart: null,
data: {},
people: '',
}
},
computed: {
option() {
var self = this;
return {
tooltip: {
trigger: 'axis'
},

dataZoom: {
show: false,
start: 0,
end: 100
},
xAxis: [{
type: 'category',
boundaryGap: true,
data: (function() {
var now = new Date();
var res = [];
var len = 10;
while (len--) {
res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''));
now = new Date(now - 2000);
}
return res;
})()
}, {
type: 'category',
boundaryGap: true,
data: (function() {
var res = [];
var len = 10;
while (len--) {
res.push(self.people);
}
return res;
})()
}],
yAxis: [{
type: 'value',
scale: true,
name: '人数',
}],
series: [{
name: '人数',
type: 'line',
data: (function() {
var res = [];
var len = 10;
while (len--) {
res.push(self.people);
}
return res;
})()
}]
}
}
},
mounted() {
this.initChart();
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose();
this.chart = null;
},
methods: {

initChart() {
var that = this;
this.chart = echarts.init(document.getElementById(this.id));
this.axios.post('url', {
id: 1
}).then((data) => {
// 初始化数据
this.data = data.data.data
this.people = this.data.expo_audience
this.chart.setOption(this.option)

// 图表动态改变
setInterval(function() {
var axisData = (new Date()).toLocaleTimeString().replace(/^\D*/g, '');
var data0 = that.option.series[0].data;
data0.shift();
// 两秒请求一次数据
that.axios.post('/url', {
id: 1
}).then((data) => {
var people = data.data.data.expo_audience
data0.push(people);
that.option.xAxis[0].data.shift();
that.option.xAxis[0].data.push(axisData);
that.option.xAxis[1].data.shift();
that.option.xAxis[1].data.push(people);

that.chart.setOption(that.option);
})
}, 2100);
})

}
}
}

</script>