后端
  • Pageable 是Spring定义的接口,用于分页参数的传递
  • Page 用于保存和返回数据 ```java //总页数 int getTotalPages();

//总数据条数 long getTotalElements();

  1. 1. Service
  2. ```java
  3. // 查询指定用户的消息
  4. public Page<Message> listUserMessage(int uid, int page, int size) {
  5. Pageable pageable = PageRequest.of(page, size, Sort.by("createTime").descending());
  6. return messageRepository.findByUid(uid, pageable);
  7. }
  1. Controller
  1. // 获取用户的消息
  2. @GetMapping("/message/page/{page}/{size}")
  3. public Map listUserMessage(@PathVariable int page, @PathVariable int size, @RequestAttribute int uid) {
  4. Page<Message> pages = notifyService.listUserMessage(uid, page, size);
  5. return Map.of("content", pages.getContent(), "total", pages.getTotalElements());
  6. }

前端

element-ui

  1. <el-pagination
  2. @prev-click="handlePrev"
  3. @next-click="handleNext"
  4. @current-change="handleCurrentChange"
  5. :hide-on-single-page="total < 10 ? true : false"
  6. small background
  7. layout="prev, pager, next"
  8. :total="total"
  9. :page-size="10">
  10. </el-pagination>
  1. data() {
  2. return {
  3. messages: [],
  4. total: 0
  5. };
  6. },
  7. created() {
  8. // 消息
  9. getMessages(0, 10).then(res => {
  10. this.messages = res.data.content || [];
  11. this.total = res.data.total || 0;
  12. });
  13. },
  14. methods: {
  15. // 分页获取数据
  16. handleCurrentChange(val) {
  17. getMessages(val - 1, 10).then(res => {
  18. this.messages = res.data.content;
  19. });
  20. },
  21. handlePrev(val) {
  22. getMessages(val - 1, 10).then(res => {
  23. this.messages = res.data.content;
  24. });
  25. },
  26. handleNext(val) {
  27. getMessages(val - 1, 10).then(res => {
  28. this.messages = res.data.content;
  29. });
  30. }
  31. }