后端处理
要想实现分页,我们的数据量要比较大才行,我们可以使用 SpringBootTest 往数据库中批量添加数据。
1、引入依赖
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、在 maven 项目的 test 目录下新建 ArticleServiceTest 插入20条测试数据
package pers.qianyucc.qblog.service;
import cn.hutool.core.util.*;
import lombok.extern.slf4j.*;
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.context.*;
import org.springframework.test.context.junit4.*;
import pers.qianyucc.qblog.*;
import pers.qianyucc.qblog.dao.*;
import pers.qianyucc.qblog.model.entity.*;
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {BlogApplication.class})
public class ArticleServiceTest {
@Autowired
private ArticleMapper articleMapper;
@Test
public void insArticle() {
ArticlePO article = articleMapper.selectById("5f008d6c4acfc62d3e96d00a");
for (int i = 0; i < 20; i++) {
article.setId(IdUtil.objectId());
article.setTitle("测试数据" + i);
articleMapper.insert(article);
}
}
}
前端
因为我们在搭建基本环境的时候后端已经封装了分页信息,所以前端就比较简单了
1、使用 Element-UI 的分页组件
<el-pagination
background
@current-change="handleCurrentChange"
:current-page.sync="pageInfo.current"
:page-size="pageInfo.size"
layout="prev, pager, next, jumper"
:total="pageInfo.total"
:hide-on-single-page="true"
></el-pagination>
说明:
- hide-on-single-page 属性设置为true的时候,当只有1页的时候不显示分页
- background 属性可以给分页加上背景色
- current-page:当前页数
- @current-change :currentPage 改变时会触发
- page-size:每页显示条目个数
- layout:组件布局,子组件名用逗号分隔
2、实现 handleCurrentChange 方法
import request from "@/http/request";
import { mapState } from "vuex";
export default {
name: "Home",
data() {
return {
pageInfo: {}
};
},
computed: mapState(["blogInfo"]),
components: {
BlogInfo: () => import("@/components/BlogInfo.vue")
},
created() {
this.getPageArticles(1, 5);
},
methods: {
handleCurrentChange(page) {
this.getPageArticles(page, 5);
},
getPageArticles(page, limit) {
request
.getArticles(page, limit)
.then(res => {
if (res.code === 0) {
this.pageInfo = res.data;
} else {
this.$notify.error({
title: "提示",
message: res.msg
});
}
})
.catch(err => {
console.log(err);
this.$notify.error({
title: "提示",
message: "网络忙,文章获取失败"
});
});
}
}
};
再对分页组件进行简单的居中处理即可
.el-pagination {
margin: 20px 0;
text-align: center;
}
效果如图:
参考代码:https://gitee.com/qianyucc/QBlog2/tree/v-7.0