分页(Springboot+vue+element-ui)
前端
*添加分页ui组件
<el-pagination style="text-align: center"
layout="prev, pager, next"
@current-change="handleCurrentChange"
:page-size="pagesize"
:current-page="currentpage"
:total="total">
</el-pagination>
*在data中设定默认值
data: {
total:'',
currentpage:1,
pagesize:8,
},
*在methods中用函数接收用户点击的当前页码(下文统一用currentpage)(以及一页的数据量(下文统一用pagesize),我这里没做)
handleCurrentChange(currentpage){
this.currentpage=currentpage;
this.getAllByPage();
},
*在(同样是methods中)getAllByPage函数中发送ajax请求currenpage和pagesize两个参数以及接收后端的表单对象-参数和总数-参数(下文统一用total)
getAllByPage(){ axios.get("/books/"+this.currentpage+"/"+this.pagesize).then((res)=>{
this.total=res.data.total;
this.tableData=res.data.data;
});
},
后端
*Controller中调用服务层getCount方法获得total参数,然后根据”起始查询数(下文统一用begin)=(currentpage-1)×pagesize’‘算出起始查询的那个数据(也就是sql语句中limit的第一个参数---begin);接着调用getAllByPage方法,将begin和pagesize传入,返回查询到的list集合,然后返回前端。
@GetMapping("/{currentpage}/{pagesize}")
public Result getAllByPage(@PathVariable Integer currentpage, @PathVariable Integer pagesize) {
Integer total=bookService.getCount();
Integer begin=(currentpage - 1)*pagesize;
List<Book> bookList=bookService.getAllByPage(begin,pagesize);
Integer code=bookList!=null?Code.GET_OK:Code.GET_ERR;
String msg=bookList!=null?"":"数据查询失败,请重试!";
return new Result(code,bookList,msg,total);
这里result我单独作为了一个对象返回传到前端,只需要在前端调用属性即可获取list和total
*service层
public List<Book> getAllByPage(Integer begin,Integer pagesize);
public Integer getCount();
及实现类
@Override
public List<Book> getAllByPage(Integer begin,Integer pagesize) {
return bookDao.getAllByPage(begin,pagesize);
}
@Override
public Integer getCount() {
return bookDao.getCount();
}
数据层
@Select("select * from SSM limit #{begin},#{pagesize}")
public List<Book> getAllByPage(@Param("begin") Integer begin,@Param("pagesize") Integer pagesize);
@Select("select count(*) from SSM")
public Integer getCount();
使用:只需要在前端vue的created函数中调用this.getAllByPage()即可实现进入主页自动实现分页功能,当然每次操作完都需要重新分页查询数据,只需要在每个method调用完之后添加.finally即可
代码如下:
created() {
this.getAllByPage();
},
.finally(()=>{
this.getAllByPage();
});
避坑:由于分页组件自行决定分页数,在el标签中建议把
:page-size="pagesize"
:total="total"
:current-page="currentpage"
都写上,一个不落,不然有可能会出现数据够了但页码不够的情况!
借鉴:黑马程序员SSM中图书管理案例,但原视频没有做分页,在这补上了。