业务需求
下图的柱状图,当条目大于5的时候,实现轮播自动翻页。
开发环境
ECharts + vue
代码实现过程
export default {
data() {
return {
//后台返回的完整数据
materialsCountByTypeY :[],
materialsCountByTypeX : [],
nowPage : 1,
pageSize : 5,
totalPage : 0,
timeKey : null,
// 渲染到echarts上的数据
changshaMaterialsCountByTypeY: [],
changshaMaterialsCountByTypeX: [],
}
},
created(){
//请求后台接口
shenZhenGoodsList({...}).then((response) => {
if (response.data) {
// 记录原数据
response.data.map((e) => {
this.materialsCountByTypeY.push(e.materialTypeNm);
this.materialsCountByTypeX.push(Number(e.percentage));
});
// 判断需不需要分页
if (response.data.length > this.pageSize) {
// 如果大于5条物资信息,则需要分页
this.totalPage = Math.ceil(response.data.length / this.pageSize); //计算总页数
// 定时函数
this.timeKey = window.setInterval(() => {
this.getNewPageData();
}, 5000);
} else {
// 如果小于等于五条,则不需要分页
this.changshaMaterialsCountByTypeY = this.materialsCountByTypeY;
this.changshaMaterialsCountByTypeX = this.materialsCountByTypeX;
// 物资种类绘制
this.getTypeOfMaterial();
}
}
});
},
destroyed() {
//页面销毁时,关闭定时器
clearInterval(this.timeKey);
},
methods:{
getNewPageData(){
// slice不改变原数组,但含头不含尾
var start = this.pageSize * (this.nowPage - 1);
var stop = start + this.pageSize;
this.changshaMaterialsCountByTypeY = this.materialsCountByTypeY.slice(start, stop);
this.changshaMaterialsCountByTypeX = this.materialsCountByTypeX.slice(start, stop);
if (this.nowPage < this.totalPage) {
// page数+1
this.nowPage += 1;
}else if(this.nowPage = this.totalPage){
// page数回到1,下次从头开始
this.nowPage = 1;
}
// 物资种类绘制
this.getTypeOfMaterial();
}
}
}
此处是前端处理了翻页数据,也可以由后台进行翻页工作。