vue3+Ant Design Vue+fastapi 前后端分离 Pagination 数据分页实战演练

Pagination 数据分页实战演练

在这里插入图片描述
数据分页在项目中的使用频率是非常高的,但是对于新手来说是一个难点和痛点,这里我记录一次数据分页从环境搭建到最后页面的渲染的过程,对于新手可以用来参考,大佬勿喷高抬贵手.

环境搭建

在这里插入图片描述
fastapi-backend 后端目录
vue-frontend 前端目录
这里我只贴一些关键的代码了,文末有代码仓库可以查看完整的代码.

后端

后端采用了fastapi框架,首先安装相关依赖fastapi faker uvicorn等,具体依赖可以参考文件头部的引用.后端的搭建首先是创建fastapi的实例,和解决跨域的问题,这些很简单,官方就有现成的代码,复制过来修改,然后就是在models.py中定义数据的模型,本项目中只有一个表和简单的字段:

from database import Base
from sqlalchemy import String,Column,Integer
class Item(Base):
    __tablename__ = 'item'
    id = Column(Integer,primary_key=True,autoincrement=True)
    addr = Column(String(256), nullable=False,index=True)

然后在main.py的入口处创建数据库,并添加一些假数据.

Base.metadata.create_all(engine) # create all tables
# 创建测试数据
item_count = 999
fk = Faker(locale="zh-CN")
db = get_db()
k = get_item_count(db)
if (get_item_count(db)==0):
    for i in range(item_count):
        addr = fk.address()
        item = Item(addr=addr)
        create_item(db,item)

第一行是创建数据库,后边判断表中是否有数据,没有的话创建999条虚拟数据.

crud.py中定义了添加和查询的方法.

from sqlalchemy.orm import Session
from models import Item
def create_item(db: Session, item: Item):
    db_item = Item(addr=item.addr)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
def get_item_count(db: Session):
    return db.query(Item).count()
# offset: 表示要跳过多少条数据,limit: 表示取几条数据,
def get_items(db: Session,skip: int = 0, limit: int = 10):
    return db.query(Item).offset(skip).limit(limit).all()

分页数据后端的重点就在查询语句那里:**offset: 表示要跳过多少条数据,limit: 表示取几条数据,**根据前端返回的参数就可以查到需要的数据了.

然后就是创建fastapi的接口函数,main.py:

@app.get("/getitems")
def get_item_list(skip: int = 0, limit: int = 10,db:Session = Depends(get_db)):
    # print(skip,limit)
    data = dict()
    data["items"] = get_items(db=db,skip=skip,limit=limit)
    data["item_count"] = get_item_count(db)
    return data

至此,后端的搭建基本完成,运行main.py后,打开http://127.0.0.1:8000/docs,就可以调试接口获取数据了:
在这里插入图片描述
如果能正常的获取数据,后端的搭建至此就结束了.

前端搭建

在项目的根目录终端下:

npm init vue@latest  # 然后一路回车即可

起好前端项目的名字:vue-frontend,当然别的也可以.

安装 ant design for vue3

npm i --save ant-design-vue

安装后 配置前端下边的main.js引入ui框架.

import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import App from './App.vue'
import 'ant-design-vue/dist/antd.css';

const app = createApp(App);
app.use(Antd);
app.mount('#app');

再安装axios npm install axios

然后在前端目录的终端下:npm run dev
即可看到项目正常启动了.

前端数据的渲染

首先搭建前端的界面,这里用到了antlistpagination,在 home.vue:

<template lang="">
  <a-list bordered :data-source="items">
    <template #renderItem="{ item }">
      <a-list-item>{{ item.id }}.{{ item.addr }}</a-list-item>
    </template>
    <template #header>
      <div>列表展示</div>
    </template>
    <template #footer>
      <div><a-pagination @change="showSizeChange" v-model:current="current" :total="count" /></div>
    </template>
  </a-list>
</template>

接下来就是定义refajax的方法了:

<script setup>
import {ref} from 'vue'
import axios from 'axios'

const baseURL = 'http://localhost:8000'

const items = ref([])
const count = ref(0)
const current = ref(1)

axios.get(baseURL+'/getitems').then(function(response) {
    console.log(response.data)
    items.value = response.data.items
    count.value = response.data.item_count
})

const showSizeChange = (current,size) =>{
    console.log(current,size)
    let skip=size*(current-1)
    let limit=size
    axios.get(baseURL+'/getitems',
    {
        params:{
            skip: skip,
            limit: limit
        },
    },
    ).then(function(response) {
    console.log(response.data)
    items.value = response.data.items
    count.value = response.data.item_count
})
}
</script>

前端的代码很简答的,vue3极大的简化了代码,还有就是翻页的pagination封装了大量分页的逻辑控制,我们只要通过两个数据就可以控制这个前端的翻页组件,let skip=size*(current-1),这个是比较关键的代码,控制着数据返回的起始点.如果没有什么问题项目已经可以正常翻页了.

本文代码仓库:
https://github.com/bosichong/vue3-fastapi-pagination.git

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3 and FastAPI are two different technologies that can be used together to build a full-stack web application. Vue3 is a popular front-end JavaScript framework that allows developers to build interactive and reactive user interfaces. It provides a powerful set of tools for building single-page applications (SPAs) and can be used with other front-end technologies like Vuex, Vue Router, and Vue CLI. FastAPI, on the other hand, is a modern, fast, and scalable web framework for building APIs with Python. It provides a simple and intuitive way to build APIs using a combination of Python type hints and async/await syntax. When used together, Vue3 and FastAPI can help developers build powerful and scalable full-stack web applications. Vue3 can be used to build the front-end UI and interact with the API endpoints provided by FastAPI. FastAPI can be used to handle requests, perform business logic, and interact with a database. To build a full-stack web application with Vue3 and FastAPI, developers can follow these steps: 1. Set up a FastAPI project with a database (e.g., PostgreSQL). 2. Define the API endpoints using FastAPI's decorators and async/await syntax. 3. Build the Vue3 front-end application with components, routing, and state management. 4. Use Axios or another HTTP client to make API requests from the Vue3 application. 5. Connect the Vue3 application to the FastAPI backend to perform CRUD operations on the database. Overall, Vue3 and FastAPI provide a powerful combination for building modern web applications that are responsive, scalable, and easy to maintain.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这里不提提纳里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值