文章目录
🌟前言🌟先看效果🌟整体代码(详细注释)🌟写在最后
🌟前言
哈喽小伙伴们,最近公司有个小需求,就是基于Echarts的折线图,做一个数据直播的功能;拿到所有图表数据之后,通过点击播放,暂停,选择播放倍数来实现相应的效果,更直观的为客户展现数据变化的过程;那接下来我们一起来看看吧
🌟先看效果
Echarts折线图逐点播放
🌟整体代码(详细注释)
DOCTYPE html>
Echarts折线图逐点播放
播放
暂停
new Vue({
el: '#app',
data: function () {
return {
myChart: null, // Echarts实例
timer: null, // 定时器
speed: 1000, // 播放速度,单位ms
// 折线图数据
data: [10, 52, 200, 334, 390, 330, 220,10, 52, 200, 334, 390, 330, 220],
// x轴数据
xData: ['周一', '周二', '周三', '周四', '周五', '周六', '周日', '周一', '周二', '周三', '周四', '周五', '周六', '周日'],
newData: [], // 新的y轴数据
newXData: [], // 新的x轴数据
currentIndex: 0 // // 定义一个变量保存当前播放到的点
}
},
mounted() {
this.initChart()
},
methods: {
// 初始化
initChart() {
// 初始化Echarts
this.myChart = echarts.init(document.getElementById('line-chart'));
// 绘制折线图
this.myChart.setOption({
xAxis: {
type: 'category',
data: this.xData
},
yAxis: {
type: 'value'
},
series: [{
type: 'line',
data: this.data
}]
});
let that = this
// 监听浏览器变化,使图表大小也随之变化
window.addEventListener('resize', function () {
that.myChart.resize()
})
},
// 播放
startPlay() {
let that = this
// 开启定时器
this.timer = setInterval(function () {
// 将第一个数据作为吃书播放的点
that.newData.push(that.data[that.currentIndex]);
that.newXData.push(that.xData[that.currentIndex])
// 如果当前点已经是最后一个,就清除定时器和数据
if (that.currentIndex > that.xData.length - 1) {
clearInterval(that.timer);
that.$message.success('完成')
that.currentIndex = 0
that.newXData = []
that.newData = []
return;
}
// // 更新每个点的数值
that.myChart.setOption({
xAxis: {
type: 'category',
data: that.newXData
},
yAxis: {
type: 'value'
},
series: [{
type: 'line',
data: that.newData
}]
});
that.currentIndex++;
}, this.speed);
},
// 暂停
stopPlay() {
clearInterval(this.timer);
}
}
})
🌟写在最后
✨原创不易,还希望各位大佬支持一下! 👍 点赞,你的认可是我创作的动力! ⭐️ 收藏,你的青睐是我努力的方向! ✏️ 评论,你的意见是我进步的财富!
|