pager.js
3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
'use strict';
const _ = require('lodash');
const handleFilterUrl = (originParam, newParam, delParam) => {
let dest = '?';
let tempOriginParam = {};
delParam = delParam || {};
tempOriginParam = Object.assign(tempOriginParam, originParam, newParam);
delete tempOriginParam.uid;
_.forEach(tempOriginParam, function(value, key) {
if (!delParam[key] && value) {
dest += `${key}=${value}&`;
}
});
return _.trim(dest, '&');
};
exports.handlePagerData = (total, params) => {
let result = {
prePage: {
url: ''
},
nextPage: {
url: ''
},
pages: []
};
let currentPage = parseInt(_.get(params, 'page', 1), 10); // 当前页
let perPageCount = parseInt(_.get(params, 'limit', 10), 10); // 每页商品数
let totalPage = _.ceil(total / perPageCount); // 总页数
result.count = total;
result.curPage = currentPage;
result.totalPages = totalPage;
if (currentPage === 1) {
// 当前页为 1,一定没有上一页
delete result.prePage;
} else {
result.prePage.url = handleFilterUrl(params, {page: currentPage - 1});
}
if (currentPage === totalPage) {
// 当前页为最后一页,一定没有下一页
delete result.nextPage;
} else {
result.nextPage.url = handleFilterUrl(params, {page: currentPage + 1});
}
if (totalPage === 1) {
return result;
}
// 页码临时数据
let pages = [];
if (currentPage > 2 && currentPage <= totalPage - 2) {
for (let i = currentPage - 2; i <= ((currentPage + 2) > totalPage ? totalPage : (currentPage + 2)); i++) {
pages.push({
url: handleFilterUrl(params, {page: i}),
num: i,
cur: currentPage === i
});
}
// 处理页码小于等于 2 的情况
} else if (currentPage <= 2) {
for (let i = 1; i <= (totalPage < 5 ? totalPage : 5); i++) {
pages.push({
url: handleFilterUrl(params, {page: i}),
num: i,
cur: currentPage === i
});
}
} else if (currentPage > totalPage - 2) {
for (let i = totalPage; i >= totalPage - 4; i--) {
if (i > 0) {
pages.push({
url: handleFilterUrl(params, {page: i}),
num: i,
cur: currentPage === i
});
}
}
pages = _.sortBy(pages, ['num']);
}
let prevPages = [];
let nextPages = [];
if (_.size(pages) === 5) {
if (currentPage > 4) {
prevPages.push({
url: handleFilterUrl(params, {page: 1}),
num: 1
});
prevPages.push({
num: '...'
});
}
if (currentPage < totalPage - 2 && totalPage > 5) {
nextPages.push({
num: '...'
});
nextPages.push({
url: handleFilterUrl(params, {page: totalPage}),
num: totalPage
});
}
}
result.pages = _.concat(prevPages, pages, nextPages);
return result;
};