pager.js
3.02 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
const _ = require('lodash');
/**
* 处理用于筛选的 URL , 拼接 URL 参数
* @param originParam 当前 URL 中的参数
* @param newParam 要拼接的 参数
* @returns {string}
*/
const handleFilterUrl = (baseUrl, originParam, newParam, delParam) => {
let dest = '?';
let tempOriginParam = {};
delParam = delParam || {};
tempOriginParam = Object.assign(tempOriginParam, originParam, newParam);
delete tempOriginParam.uid;
_.forEach(tempOriginParam, (value, key) => {
if (!delParam[key] && value) {
// NOTE: 这里会对 query 进行编码,因为 query 有可以能是中文
if (key === 'query') {
value = encodeURIComponent(value);
}
dest += `${key}=${value}&`;
}
});
return (baseUrl || '') + _.trim(dest, '&');
};
module.exports = (total, params = {}, baseUrl = '') => {
const curPage = _.parseInt(params.page || 1);
const pageSize = _.parseInt(params.limit) || 10;
const totalPage = _.ceil(total / pageSize);
const tip = {
start: (curPage - 1) * pageSize + 1,
end: curPage * pageSize > total ? total : curPage * pageSize,
total
};
let prePage, nextPage;
const pageUrl = handleFilterUrl(baseUrl, params, {page: '${page}'});
if (curPage > 1) {
prePage = {
url: pageUrl.replace('${page}', curPage - 1)
};
}
if (curPage < totalPage) {
nextPage = {
url: pageUrl.replace('${page}', curPage + 1)
};
}
let pages = [];
let pagesNums = totalPage > 5 ? 5 : totalPage;
let offsetPage = curPage + _.round(0 - pagesNums / 2); // 遍历页码左侧数字
if (offsetPage <= 0) {
offsetPage = 1;
} else if (offsetPage + pagesNums > totalPage) {
offsetPage = totalPage - pagesNums + 1;
}
const preLimit = offsetPage - 1; // 页码1和遍历页码左侧的距离
const nextLimit = totalPage - (offsetPage - 1 + pagesNums); // 总页码和遍历页码右侧的距离
if (preLimit === 1) { // 如果左侧间距为1则显示这个页码
pagesNums++;
offsetPage--;
}
if (nextLimit === 1) { // 如果右侧间距为1则显示这个页码
pagesNums++;
}
if (preLimit >= 2) {
pages = _.concat(pages, {
num: 1,
url: pageUrl.replace('${page}', 1),
}, {
num: '...'
});
}
if (offsetPage <= 0) {
offsetPage = 1;
} else if (offsetPage + pagesNums > totalPage) {
offsetPage = totalPage - pagesNums + 1;
}
for (let i = 0; i < pagesNums; i++) {
pages.push({
num: offsetPage,
url: pageUrl.replace('${page}', offsetPage),
cur: curPage === offsetPage
});
offsetPage++;
}
if (nextLimit >= 2) {
pages = _.concat(pages, {
num: '...'
}, {
num: totalPage,
url: pageUrl.replace('${page}', totalPage),
});
}
return {tip, prePage, nextPage, pages};
};