后端
- Pageable 是Spring定义的接口,用于分页参数的传递
- Page 用于保存和返回数据 ```java //总页数 int getTotalPages();
//总数据条数 long getTotalElements();
1. Service
```java
// 查询指定用户的消息
public Page<Message> listUserMessage(int uid, int page, int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
return messageRepository.findByUid(uid, pageable);
}
- Controller
// 获取用户的消息
@GetMapping("/message/page/{page}/{size}")
public Map listUserMessage(@PathVariable int page, @PathVariable int size, @RequestAttribute int uid) {
Page<Message> pages = notifyService.listUserMessage(uid, page, size);
return Map.of("content", pages.getContent(), "total", pages.getTotalElements());
}
前端
element-ui
<el-pagination
@prev-click="handlePrev"
@next-click="handleNext"
@current-change="handleCurrentChange"
:hide-on-single-page="total < 10 ? true : false"
small background
layout="prev, pager, next"
:total="total"
:page-size="10">
</el-pagination>
data() {
return {
messages: [],
total: 0
};
},
created() {
// 消息
getMessages(0, 10).then(res => {
this.messages = res.data.content || [];
this.total = res.data.total || 0;
});
},
methods: {
// 分页获取数据
handleCurrentChange(val) {
getMessages(val - 1, 10).then(res => {
this.messages = res.data.content;
});
},
handlePrev(val) {
getMessages(val - 1, 10).then(res => {
this.messages = res.data.content;
});
},
handleNext(val) {
getMessages(val - 1, 10).then(res => {
this.messages = res.data.content;
});
}
}