原理:分页的底层原理就是利用了sql命令中的limit 关键字,通过sql 语句查询数据。
构建分页器
from utils.dataBase import MySQL
class Paginator:
"""
分页器
"""
def __init__(self, total=0, current_page=1, page_size=1):
self.total = int(total)
self.current_page = int(current_page)
self.page_size = int(page_size)
if self.page_size <= 0 or self.current_page <= 0:
self.page_size = 1
self.current_page = 1
def page_num(self):
if self.total % self.page_size == 0:
return self.total // self.page_size
else:
return self.total // self.page_size + 1
def get_data(self, sql):
_limit = (self.current_page - 1) * self.page_size
_offset = self.page_size
sql += f" limit {_limit},{_offset}"
db = MySQL()
return db.get_all(sql)
flask中使用分页器
@course.route('/test/', methods=['GET'])
def get_course():
current_page = request.args.get("current_page", 1)
page_size = request.args.get("page_size", 1)
db = MySQL()
sql = "select count(1) as total from `course`"
result = db.get_one(sql)
p = Paginator(result['total'], current_page, page_size)
page_num = p.page_num()
sql = "select * from `course` order by `id` desc"
result = p.get_data(sql)
return {"code": 200, "page_num": page_num, "data": result}
vue中使用分页器
<template>
<div>
<table style="margin: auto;text-align: center;">
<tr>
<th>课程编号</th>
<th>课程标题</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in courses">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
<td>
<van-button>删除课程</van-button>
<van-button>编辑课程</van-button>
</td>
</tr>
</table>
<div>
一共有{{ page_num }}页 , 当前页:{{ current_page }}
<ul>
<li v-show="last_page" @click="get_data(last_page)">上一页</li>
<li v-for="index in page_num">
<a @click="get_data(index)"> {{index}}</a>
</li>
<li v-show="next_page" @click="get_data(next_page)">下一页</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
courses: [],
current_page: 1,
page_size: 1,
page_num: 0,
last_page: 0,
next_page: 0,
}
},
methods: {
get_data(index) {
if (index) {
this.current_page = index
}
this.axios.get('http://127.0.0.1:5000/test/', {
params: {
'current_page': index,
'page_size': this.page_size
}
}).then(result => {
this.courses = result.data.data
this.page_num = result.data.page_num
if (index === 1) {
this.last_page = 0;
} else {
this.last_page = index - 1;
}
if (index === this.page_num) {
this.next_page = 0;
} else {
this.next_page = index + 1;
}
})
}
},
mounted() {
this.get_data()
}
}
</script>
<style scoped>
li {
display: inline-block;
}
</style>
感谢观看!
|