自学内容网 自学内容网

【vue3】分页功能实现(nodejs)

分页查询
在前端中分页查询的出现是为了让有一定数据量的页面能够更合理的展示出来,同时结合Element Ui提供的分页组件,能够对前端展示的数据做更多的操作。

前端代码

<el-pagination background layout="total, prev, pager, next" 
    :total="total" 
    v-model:page-size="pageSize"
@current-change="handelpage(currentPage)" 
v-model:current-page="currentPage" 
style="margin-top: 40px;float: right;" />
// 获取文章列表数据
let tableData = reactive([])
let currentPage = ref(1)
let pageSize = ref()
const total = ref()
console.log(currentPage)
async function getArt() {
try {
const response = await getArticles(currentPage.value); // 假设 getArticles() 返回一个 Promise  
console.log(response);
// 更新 tableData 数组的内容,而不是替换它的引用  
total.value = response.data.total
tableData.splice(0, tableData.length, ...response.data.data);
} catch (error) {
console.error('获取文章列表失败:', error);
}
}
const handelpage = () => {
console.log(currentPage.value);
getArt()
}

后端代码

//获取全部文章信息账单
router.get('/getArticle', (req, res, next) => {
console.log(req.query)
const page = parseInt(req.query.page) || 1;  // 分页数量,默认为1
  const size = parseInt(req.query.size) || 10;  // 分页大小,默认为10
  const skip = (page - 1) * size;
 
// 首先查询总记录数  
    accountModel.countDocuments().then(totalCount => {  
        // 然后根据分页参数查询文章列表  
        accountModel.find()  
            .sort({ createTime: -1 })  
            .skip(skip)  
            .limit(size)  
            .then(data => {  
                res.json({  
                    code: '20000',  
                    msg: '找到了',  
                    total: totalCount, // 使用正确的拼写和从数据库获取的总数  
                    data: data  
                });  
            })  
            .catch(err => {  
                res.json({  
                    code: '1002',  
                    msg: '读取失败',  
                    data: null  
                });  
                next(err); // 传递错误给错误处理中间件(如果有的话)  
            });  
    })  
    .catch(err => {  
        res.json({  
            code: '1001', // 可以为计数失败定义一个不同的错误代码  
            msg: '计数失败',  
            data: null  
        });  
        next(err); // 传递错误给错误处理中间件(如果有的话)  
    });  
})


原文地址:https://blog.csdn.net/aaaa_aaab/article/details/142779452

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!