nodejs+vue分页实现

16 篇文章 0 订阅

fenye.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>分页</title>
    <style>
        .btnSelect{
            background-color: royalblue;
        }
    </style>
</head>
<body>
<div id="pages">
    <table>
        <tbhead></tbhead>
        <tbody>
            <tr v-for="obj in pageData">
                <td>{{obj.uid}}</td>
                <td>{{obj.uname}}</td>
                <td><a @click="deleUser()">删除</a></td>
            </tr>
        </tbody>
        <tfoot>
            <button @click="getPage(1)">首页</button>
            <button @click="prePage()" :disabled="curPage==1" >上一页</button>
            <button v-for="(item,index) in list" @click="getPage(index+1)" v-bind:class="{btnSelect:curPage==(index+1)}">{{index+1}}</button>
            <!--<button @click="getPage(1)" v-bind:class="{btnSelect:curPage==1}">1</button>
            <button @click="getPage(2)" v-bind:class="{btnSelect:curPage==2}">2</button>
            <button @click="getPage(3)" v-bind:class="{btnSelect:curPage==3}">3</button>-->
            <button @click="nextPage()" :disabled="curPage==pageCount">下一页</button>
            <button @click="lastPage()">尾页</button>
        </tfoot>
    </table>
</div>

<script type="text/javascript" src="js/vue.js"></script>
<script src="js/ajax.js"></script>
<script type="text/javascript">
    Vue.component('tbhead',{
        template:`
				<thead>
					<tr>
						<td>编号</td>
						<td>用户名</td>
						<td>操作</td>
					</tr>
				</thead>
			`
    });

    var app=new Vue({
        el:'#pages',
        data:{
            list:[1,2,3],
            curPage:1,
            pageSize:3,
            pageCount:0,
            pageData:null
        },
        methods:{
            init(){
                ajax({
                    type:"get",
                    url:"/init",
                    data:`pageSize=${this.pageSize}`,
                    dataType:"json"
                }).then(data=>{
                    this.pageCount=data.pageCount;
                })
            },
            getPage(curPage){
                ajax({
                    type:"get",
                    url:"/page",
                    //这里写成app.pageSize,不用this,防止下面调用该函数时this的指向发生改变
                    data:`curPage=${curPage}&pageSize=${app.pageSize}`,
                    dataType:"json"
                }).then(data=>{
                    app.pageData=data;  //必须用app.,不能用this,不然会由于this指向的改变发生错误
                    app.curPage=curPage;
                })
            },
            prePage(){
                if(this.curPage==1){
                    return;
                }
                this.$options.methods.getPage(this.curPage-1);
                --this.curPage;
            },
            nextPage(){
                if(this.curPage>=this.pageCount){
                    return;
                }
                this.$options.methods.getPage(this.curPage+1);
                ++this.curPage;
            },
            lastPage(){
                this.$options.methods.getPage(this.pageCount);
            },
            deleUser(uid){

            }
        }
    });

    app.init();
    app.getPage(1);
</script>
</body>
</html>
init.js

/**
 * Created by web-01 on 2018/1/10.
 */
const mysql=require("mysql");
var pool=mysql.createPool({
    host:'127.0.0.1',
    user:"root",
    password:"",
    database:"test",
    port:3306,
    connectionLimit:25 //连接数量限制
});

module.exports.pool=pool;
app.js

/**
 * Created by web-01 on 2018/1/10.
 */
const http=require("http");
const express=require("express");
var m=require("./init.js");
var app=express();
var server=http.createServer(app);
server.listen(3000);
var pool=m.pool;

app.use(express.static('public'));

app.get("/",(req,res)=>{
    res.sendFile(__dirname+"/public/"+"fenye.html");
});

app.get("/init",(req,res)=>{
   var pageSize=req.query.pageSize;
   var sql="SELECT count(*) FROM t_user";
    pool.getConnection((err,conn)=>{
        if(err) throw err;
        conn.query(sql,(err,result)=>{
            if(err) throw err;
            var pageCount = Math.ceil(result[0]['count(*)']/pageSize);
            res.json({pageCount:pageCount});
        });
        conn.release();
    });
});

app.get("/page",(req,res)=>{
   var curPage=parseInt(req.query.curPage);
   var pageSize=parseInt(req.query.pageSize);

   var start=(curPage-1)*pageSize;

    pool.getConnection((err,conn)=>{
        if(err) throw err;
        var sql="SELECT uid,uname FROM t_user WHERE status=1 LIMIT ?,?";
        conn.query(sql,[start,pageSize],(err,result)=>{ //参数为什么没有传进去?是因为上面需要用parseInt转换
            if(err) throw err;
            res.json(result);
        });
        conn.release();
    })
});
ajax.js

//封装适合各种情况的简化版ajax函数
function ajax({//利用解构,获取将来参数对象中每个属性值
  type,//请求类型: "get"||"post"
  url,//请求的url地址: "xxx.php"
  data,//请求携带的参数: "变量1=值&..."
  dataType,//服务器端返回值类型: "json"||"text"
}){
  //服务器端返回值类型默认为text
  dataType=dataType||"text";
  //只要远程请求,必有延迟,只要延迟,比用promise等待完成后,才执行后续操作
  return new Promise(function(resolve){//.then()
    //AJAX 4步/5步:
    var xhr=new XMLHttpRequest();//1.获得xhr对象
    //如果是get请求,且传入了data参数,才需要拼接url和data为get请求的完整地址
    if(type.toLowerCase()=="get"&&data!==undefined)
      url+="?"+data;
    xhr.open(type,url,true);//2. 建立连接
    //3. 设置请求状态回调函数
    xhr.onreadystatechange=function(){
      //如果请求完成,且成功!
      if(xhr.readyState==4&&xhr.status==200){
        //如果服务器端响应类型不是json,则调用后续resolve操作,并传入原始responseText,做后续处理
        if(dataType.toLowerCase()!="json")
          resolve(xhr.responseText);
        else//如果服务器端响应类型是json,则自动调用JSON.parse转为js对象,再交给resolve函数做后续处理
          resolve(JSON.parse(xhr.responseText));
      }
    }
    //只有type为post,才需要设置请求头
    if(type.toLowerCase()=="post")
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //只有type为post,才需要send时,传入参数
    xhr.send(type.toLowerCase()=="post"?data:null);
  })
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值