这里提供两种分页方法
一种是手写分页,不常用,但是明白一下分页的逻辑实现
第二种是用heyui提供的组件.很多功能都给封装好了,用起来也比较美观.
手写分页
后端接口
class GoodList(APIView):def get(self, request):# 当前页page = int(request.GET.get('page', 1))# 一页有多少条商品size = int(request.GET.get('size', 1))# 定义从哪里开始切片data_start = (page - 1) * size# 定义切到哪data_end = page * size#查询数据goodslist=Goods.objects.all()[data_start:data_end]#查询总数量count=Goods.objects.count()# 序列化操作goods_ser=GoodsSer(goodslist,many=True)# 返回响应return Response({'total':count,'data':goods_ser.data})
前端页面
<template>
......<!--自主分页--><div><!-- v-show 判断当前页数是否有需要显示上或下一页 --><Button v-show="lastpage" @click="getdata(lastpage)">上一页</Button><Button v-for="index in all" @click="getdata(index)">{{index}}</Button><Button v-show="nextpage" @click="getdata(nextpage)">下一页</Button></div>
</template><script>export default {data() {return {//自主分页total: 0,//商品总数curpage: 1,//当前页all: 0,//总页数lastpage: 0,//上一页nextpage: 0,//下一页size: 2,//每页显示多少//商品列表goodlist: '',mounted() {//调用自主分请求this.getdata(1);},methods: {//自主分页接口getdata: function (mypage) {this.axios.get('http://localhost:8000/goodlist/', {params: {page: mypage,size: this.size}}).then(res => {this.goodlist = res.data.data;console.log(res.data.data);//判断上一页if (mypage == 1) {this.lastpage = 0;} else {this.lastpage = mypage - 1}// 计算总页数 Math.ceil 向上取整this.all = Math.ceil(res.data.total / this.size);//判断下一页if (mypage == this.all) {this.nextpage = 0} else {this.nextpage = mypage + 1}});},}}</script><style></style>
heyui 组件库
后端代码不用做修改.可以直接复用.heyui前端就相对来说简单了许多.
<template>......<!--heyui分页--><br></div><div><!-- layout可以自定义控制显示那些组件和顺序.--><Pagination v-model="pagination" @change="change" layout="sizes,pager,jumper" align="center"></Pagination></template><script>export default {data() {return {//分页器变量pagination: {page: 1,size: 3,total: 5},//商品列表goodlist: '',},mounted() {//请求商品接口返回数据this.axios.get('http://localhost:8000/goodlist/', {params: {page: 1, size: 3}}).then(res => {this.goodlist = res.data.data;console.log(res.data.data)});},methods: {//分页器事件change: function () {//二次请求this.axios.get('http://localhost:8000/goodlist/', {params: {page: this.pagination.page,size: this.pagination.size}}).then(res => {this.goodlist = res.data.data;console.log(res.data.data)});},}}</script><style></style>
两种分页的效果.上边的是heyui组件,下边是手写分页器.
HEY UI 分页文档:https://www.heyui.top/component/data/view/page
Element 组件文档:https://element.eleme.cn/#/zh-CN/component/installation
功能多多 各自挖掘吧.