项目需求:后台实时数据,页面打开获取一次真是数据就好,但是要呈现出几秒动态一次。
方法:从接口拿到数据处理好备用,
技术点: 清除 echartBar.clear();
重新压入 echartBar.setOption(optionBar);
html
<div class="item-chart" id="dangerOption" style="height:130px"> </div>
复制
js:
function echartStart(){ //此处echart我已经在main.js引入了,并且命名为`$echarts` // import Echarts from 'echarts' // Vue.prototype.$echarts = Echarts let echartBar = _this.$echarts.init(document.getElementById('dangerOption')); //重要 echartBar.clear(); let optionBar = { grid: { top: '20px', left: '10px', right: '10px', bottom: '0px', containLabel: true }, xAxis: { type: 'category', data: ['堆物堆料', '消防通道', '防火门', '电动车', '水压', '电梯'], axisLabel: { color: '#fff' }, axisLine: { lineStyle: { color: '#fff' } } }, yAxis: { type: 'value', axisLabel: { color: '#fff' }, axisLine: { lineStyle: { color: '#fff' } }, splitLine: { show: false } }, series: [{ //newData就是从接口出拿到的数据 data: newData, itemStyle: {normal: {label: {show: true}}}, type: 'line', //animationDuration: 300, //该属性设置动画速度 //animationEasing: 'quadraticln' //运行的速度类型 }] }; echartBar.setOption(optionBar); //当页面改变时,图表自适应 window.onresize = echartBar.resize; //单个 如果按照上面的代码写,只会自适应最后一个【也好像是第一个】; //多个 此处可以写一个页面resize方法,增加防抖功能 //第一步: //将echartBar 实例赋值给data中; //_this.echarts1 = echartBar; //第二步: //mounted(){ // window.addEventListener('resize',this.pageResize); //}, //第三步: //motheds:{ // pageResize(){ // clearTimeout(_this.timer); // _this.timer = null; // _this.timer = setTimeout(()=> { // //自适应方法 // this.echarts1.resize(); // },500) // } //} } //定时4s动态一次 _this.yhInterval = setInterval(function(){ echartStart(); },4*1000)
复制
在vue项目中记得在 beforeDestroy() 生命周期内将定时器销毁
beforeDestroy(){
clearInterval(_this.yhInterval);
_this.yhInterval = null;
}