在uniapp中通过uni-pagination组件实现表格内容的分页查询,实现思路和简单,分为两个步骤:
1、使用MySQL的Limit语句按照要求查询出符合分页要求的记录;
2、通过MySQL的COUNT函数获取该表中的全部记录;
接下来我们结合前两个章节的内容实现表格的分页查询。
一、分页查询微服务
在idea中使用通用Mapper(第02讲:通用Mapper)实现单表的分页查询,用户访问controller时需要传递2个参数,分别是从第start条记录开始查,每次查询pageSize条数据,controller按照要求从数据库中查询相关的记录并返回,同时返回该表中的全部记录。以下是相关代码:
mapper.xml
<select id="selectList" parameterType="int" resultMap="BaseResultMap">
select * from city order by date desc limit #{start}, #{pageSize}
</select>
service
@Autowired
private CityMapper cityMapper;
@Override
List<City> cities = cityMapper.selectList(start, pageSize);
int rows = cityMapper.selectCount(null);
return new HttpResult(200, "", cities, rows);
}
controller
@Autowired
private CityService cityService;
@GetMapping("/list")
@ResponseBody
@CrossOrigin(origins = "*") //允许跨域请求
public HttpResult getAll(int start, int pageSize){
return cityService.selectAll(start, pageSize);
}
测试:网页访问controller:http://localhost:8080/city/list?start=0&pageSize=6
二、分页查询uniapp
在uniapp中使用uni-table(第01讲:基于uniapp的小程序跨端开发),在表格下方添加uni-pagination分页器
<uni-pagination style="margin-top: 10rpx;" @change="pageChanged" :current="pageIndex" :pageSize="pageSize" :total="pageTotle"></uni-pagination>
分页器需要3个参数,分别是:
data() {
return {
...
pageIndex: 1, //分页器页码
pageSize: 6, //分页器每页显示数据的条数
pageTotle: 0, //分页器数据总条数
...
}
}
点击分页器的监听函数
// 分页器点击监听
pageChanged(e) {
// console.info("点击了分页器");
// console.info(e.type + "**");
// console.info(e.current + "**");
this.pageIndex = e.current;
this.httpGetCityList();
}
网络请求函数:
// 请求表格数据
httpGetCityList(){
uni.request({
url: 'http://localhost:8080/city/list',
data: {
start: (this.pageIndex - 1) * this.pageSize,
pageSize: this.pageSize
},
success: (res) => {
console.log(res.data.data);
this.cityList = res.data.data;
this.pageTotle = res.data.cnt;
}
});
}
最终效果: