后端
const Koa = require('koa2'); const Router = require('koa-router'); const Monk = require('monk');//鏈接mongodb數據庫中間件 const app = new Koa(); const router=new Router(); const db=new Monk('localhost/school'); const students = db.get('article'); const bodyParser = require('koa-bodyparser')//解析請求參數中間件 app.use(bodyParser()) app.use(async (ctx, next) => { console.log(`請求信息:\n 方式: ${ctx.request.method} \n 地址:${ctx.request.url}...`); ctx.set("Access-Control-Allow-Origin", "*"); await next();//相當於java的filter放行 }); router .get('/', async ( ctx ) => { ctx.response.type = 'text/html'; ctx.body = 'hi' }) .post('/vueDemo/getStudents', async ( ctx ) => { let totle = await students.count();//表總記錄數 //koa-bodyparser解析前端參數 let reqParam= ctx.request.body;// let page = Number(reqParam.page);//當前第幾頁 let size = Number(reqParam.size);//每頁顯示的記錄條數 //顯示符合前端分頁請求的列表查詢 let options = { "limit": size,"skip": (page-1)*size}; let st = await students.find({},options,function(err,docs){ if (err) {console.log(err);return;} else{console.log(docs);return;} }); //是否還有更多 let hasMore=totle-(page-1)*size>size?true:false; ctx.response.type = 'application/json'; //返回給前端 ctx.body = {hasMore:hasMore,students:st,totle:totle}; }) app.use(router.routes()); app.listen(3000, () => { console.log('[myapp]已經運行,端口為300') })
數據庫
{"name" : "小明","age" : 10.0} {"name" : "丁少華", "age" : 20} {"name" : "小張","age" : 18.0} {"name" : "王新","age" : 30.0} {"name" : "小紅","age" : 16.0}
前端
<template> <div class="artList" > <!--列表--> <ul class="content"> <li v-for="st in students"> <div>{{st.name}}</div> <div>{{st.age}}</div> </li> </ul> <!--分頁--> <div class="pageinfo"> 共{{totle}}條記錄 <button v-on:click="fy('s')">上一頁</button> <button v-on:click="fy('x')" >下一頁</button> 當前第{{page}}頁 </div> </div> </template> <script> export default { name:'artlistCmp', data() {return { page:1,totle:0,students:[],hasMore:false,title:''}}, methods:{ getStudent(){ var vm=this; this.service.getStudent({page:vm.page,size:3}).then(function(rep) { vm.totle=rep.data.totle; vm.students=rep.data.students; vm.hasMore=rep.data.hasMore; }) }, fy(param){ if(param=='x'){ if(!this.hasMore){alert('已經是最后一頁了'); return false;} this.page++ }else{ if(this.page==1){ alert('已經是首頁了');return false; } this.page-- } this.getStudent() } }, created(){this.getStudent();} } </script> <style> .artList{width: 100%} .list{width: 100%} li{ display: block; height: 140px; background-color: aliceblue; margin-bottom: 20px; } </style>
效果