pager.js
3.17 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/**
* 分页处理
* @author: yyq<yanqing.yang@yoho.cn>
* @date: 2016/8/19
*/
'use strict';
const _ = require('lodash');
/**
* 拼接url
* @function joinUrl
* @param params 要拼接的 参数
* @returns {string}
*/
const joinUrl = (params) => {
let dest = '?';
_.forEach(params, function(value, key) {
dest += `${key}=${value}&`;
});
return _.trim(dest, '&');
};
/**
* 设置分页
* @setPager setPager
* @param total 总页数
* @param params 参数
* @returns {object}
*/
exports.setPager = (total, params)=>{
let resData = {};
let cutStatus, // 切割状态 1:去头 2:去尾 3:双切
i;
let pages = [];
let currentPage = parseInt(params.page || 1, 10); // 当前页
// 小于两页直接退出
if (total < 2) {
return resData;
}
for (i = currentPage - 2; i <= currentPage + 2; i++) {
if (i < 1) {
cutStatus = 1;
continue;
}
if (i > total) {
cutStatus = cutStatus ? 3 : 2;
continue;
}
pages.push({
url: joinUrl(Object.assign(params, {page: i})),
num: i,
cur: currentPage === i
});
}
// 分页中部补全
let len = 5 - pages.length;
let list = [];
if (cutStatus === 1) {
for (i = 1; i <= len; i++) {
let p = currentPage + i + 2;
if (p > total) {
break;
}
list.push({
url: joinUrl(Object.assign(params, {page: p})),
num: p
});
}
pages = _.concat(pages, list);
} else if (cutStatus === 2) {
for (i = 1; i <= len; i++) {
let p = currentPage - i - 2;
if (p < 1) {
break;
}
list.push({
url: joinUrl(Object.assign(params, {page: p})),
num: p
});
}
pages = _.concat(list, pages);
}
// 分页头尾补全
let fnum = _.get(_.head(pages), 'num', 1),
lnum = _.get(_.last(pages), 'num', 1);
if (fnum > 1) {
if (fnum > 2) {
pages = _.concat({
url: joinUrl(Object.assign(params, {page: 1})),
num: 1
}, {num: '...'}, pages);
} else {
pages = _.concat({
url: joinUrl(Object.assign(params, {page: 1})),
num: 1
}, pages);
}
}
if (lnum < total) {
if (lnum < total - 1) {
pages = _.concat(pages, {num: '...'}, {
url: joinUrl(Object.assign(params, {page: total})),
num: total
});
} else {
pages = _.concat(pages, {
url: joinUrl(Object.assign(params, {page: total})),
num: total
});
}
}
resData.pages = pages;
// 上一页
if (currentPage > 1) {
resData.prePage = {url: joinUrl(Object.assign(params, {page: currentPage - 1}))};
}
// 下一页
if (currentPage < total) {
resData.nextPage = {url: joinUrl(Object.assign(params, {page: currentPage + 1}))};
}
return resData;
};