記錄一次vue3+Naive UI+fastapi 前后端分離 Pagination 數(shù)據分頁實戰(zhàn)演練的過程。
Naive UI 是一個 Vue3 的組件庫。
FastAPI 是一個用于構建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于標準的 Python 類型提示。
fastapi-backend
后端目錄vue-frontend
前端目錄
這里我只貼一些關鍵的代碼了,文末有代碼倉庫可以查看完整的代碼.
后端
后端fastapi的搭建請看這里,就不在重復了
前端
Vue 及 Naive UI 的創(chuàng)建
在項目的根目錄終端下:
npm init vue@latest # 然后一路回車即可
安裝及引入Naive UI
npm i -D naive-ui
安裝后 配置前端下邊的main.js引入Naive UI框架.
import { createApp } from 'vue'
import App from './App.vue'
import naive from 'naive-ui'
const app = createApp(App);
app.use(naive);
app.mount('#app');
安裝axios npm install axios
然后在前端目錄的終端下:npm run dev
即可看到項目正常啟動了.
前端的數(shù)據渲染
創(chuàng)建Home.vue,在App.vue中引入。
Home.vue 中配置一個簡單的列表和分頁組件:
<template>
<n-list>
<n-list-item v-for="item in items" :key="item.id">
{{ item }}
</n-list-item>
</n-list>
<n-pagination v-model:page="current" :item-count="count" :on-update:page="showSizeChange" />
</template>
其中v-model:page是當前頁碼數(shù),item-count是數(shù)據的總條數(shù)。:on-update:page="showSizeChange"是當前頁碼數(shù)發(fā)生變化后的響應。
再看Vue中的js代碼:
<script setup>
import { ref, watch } from 'vue'
import axios from 'axios'
const baseURL = 'http://localhost:8000'
const items = ref([]) // 數(shù)據
const count = ref(0) // 數(shù)據總條數(shù)
const current = ref(1) // 當前頁面
const size = ref(10) // 每頁顯示的條數(shù)
// :on-update:page 事件 來控制獲取當前頁面的頁碼數(shù)
const showSizeChange = (page,) => {
console.log(current.value, size.value)
current.value = page
}
// 翻頁方法
const nextPage = () => {
let skip = size.value * (current.value - 1)
let limit = size.value
console.log(skip, limit)
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
})
}
// 默認加載第一頁的數(shù)據
nextPage()
// 偵聽器,用來檢測頁碼變化后執(zhí)行翻頁方法
watch(current,nextPage)
</script>
nextPage()根據當前頁碼數(shù)加載數(shù)據,watch(current,nextPage)用來檢測頁碼變化后執(zhí)行翻頁方法,let skip = size.value * (current.value - 1),這個是比較關鍵的代碼,控制著數(shù)據返回的起始點.與后端的return db.query(Item).offset(skip).limit(limit).all()代碼時對應的。
最后運行代碼效果如下:
本文代碼倉庫地址:文章來源:http://www.zghlxwxcb.cn/news/detail-461654.html
https://github.com/bosichong/vue3-fastapi-pagination/tree/naive_Pagination文章來源地址http://www.zghlxwxcb.cn/news/detail-461654.html
到了這里,關于vue3+Naive UI+fastapi 前后端分離 Pagination 數(shù)據分頁實戰(zhàn)演練的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!