1: echarts 动态刷新的实现
1.1: 从小到大的排序
1.2: 每五个元素显示一页 (currentPage, totalPage)
2: 启动和停止时机:
启动: 获取数据之后穷启动定时器
鼠标移出图表时启动定时器
停止: 组件销毁时停止定时器
鼠标移入图表图表时启动定时
3: 边界值的判断(处理) 判断currentPage 是否大于totalPage
-------------------------------------------------------
// 商家销售统计的横向柱状图
<template>
<div class="com-container">
<div class="com-charts" ref="seller_ref">
</div>
</div>
</template>
<script>
export default {
data() {
return {
chartsInstance = null, // 保存chartsInstance 数据
allData: null, // 服务器返回的数据
currentPage: 1, // 当前显示的页数
totalPage: 0, // 一共显示多少页
timerId: null, // 定时器的标识
}
},
mounted() {
this.initCharts(),
this.getData(),
},
// 组件销毁的时候, 取消定时器
destroyed() {
clearInterval(this.timerId)
},
methods: {
// 初始化 chartsInstance 对象
initCharts () {
this.chartsInstance = this.$echrts.init(this.$refs.seller_ref);
// 对图标对象进行鼠标事件的监听
this.chartInstance.on('mouseover', ()=> { // 鼠标进入事件清除定时器
clearInterval(this.timerId)
})
this.chartInstance.on('mouseout', ()=> { // 鼠标离开事件开启定时器
startInterval(this.timerId)
})
},
// 获取服务器的数据
async getData() {
// 访问服务器地址对象 // http:// 172.0.0.1:8089/api/seller
const {data: ret} await this.$http({
url: 'seller',
method: 'get'
})
console.log(ret)
this.allData = ret;
// 对数组进行排序的操作
this.allData.sort((a, b)=> {
return a.value < b.value // 从小到大的排序
})
// 每五个元素显示一页
this.totalPage = this.allData.lemgth % 5 === 0 ? this.allData.lemgth % 5 :
this.allData.lemgth % 5 + 1
this.updateCharts() // 第一次图标的更新
this.startInterval(); // 开启定时器
}
// 更新图表
updateCharts() {
const start = (this.currentPage - 1) * 5; // 0
const end = this.currentPage * 5; // 5
const showData = this.allData.slice(start, end)
const sellerNames = showData.map((item)=> {
return item.name
})
const sellerValues = showData.map((item)=> {
return item.value
})
const option = {
xAis: {
type: 'value'
},
yAxis: {
type: 'category'
data: sellerNames
},
series: [
{
type: 'bar',
data: sellerValues
}
]
},
this.chartsInstance.setOption(option);
},
startInterval () {
if(this.timerId) {
clearInterval(this.timerId)
}
this.timerId = setInterval(()=> {
this.currentPage++;
if(this.currentPage < this.totalPage) {
this.currentPage = 1
}
this.updateChart();
}, 5000) // 间隔5 s 刷新一次
}
}
}
</script>
<style lang="less" scoped>
</style>
Echarts 动态刷新的实现
最新推荐文章于 2023-11-23 09:48:19 发布
该博客介绍了如何使用Echarts创建一个动态刷新的横向柱状图,数据从小到大排序,每五个元素显示一页。启动和停止刷新的时机分别在获取数据后和鼠标移出图表时,而停止则在组件销毁和鼠标移入图表时。同时,文章详细讲解了如何处理边界值,确保currentPage不超过totalPage。示例代码展示了具体的实现过程,包括数据获取、图表初始化、更新图表和定时器管理等步骤。
摘要由CSDN通过智能技术生成