
通過學習Vue,的確覺的Vue的雙向綁定使用起來十分方便,因此研究了一下列表顯示時分頁的實現,這里我使用了bootstrap的樣式,所以在頁面中引用bootstrap的樣式文件,后台提數據源使用.net的,數據庫訪問使用EF,如果庫中存有大量數據,為提高顯示速度還是建議使用更好的數據訪問方式,比如dapper,下面看看我的實現 :
1、首先創建一個分頁的類PageList,封裝其分頁所需的各值:
public class PageList { /// <summary> /// 初始化 /// </summary> /// <param name="curPage">當前頁</param> /// <param name="total">記錄數</param> /// <param name="pagesize">每頁顯示的記錄數</param> /// <param name="showPageNum">頁碼顯示數量</param> public PageList(int curPage, int total,int pagesize=10,int showPageNum=9) { this.total = total; this.pagesize = pagesize; this.curPage = curPage; this.showPageNum = showPageNum; this.firstNum = 1; this.lastNum = this.totalPages; this.pagelist = this.getPagelist(); } //前面的點,前面省略的頁數用.來代表, public bool previousSpot { get; set; } //后面的點,后面省略的頁數用.來代表, public bool nextSpot { get; set; } //第一個頁數,一般都是1 public int firstNum { get; set; } //最后一個頁數,也就是最大頁數 public int lastNum { get; set; } //默認頁面顯示最多頁號數目 public int showPageNum { get; set; } public int total { get; set; }//總記錄數 //總頁數 public int totalPages { get { return (int)Math.Ceiling((double)total / pagesize); } } public int curPage { get; set; }//當前頁 public int pagesize { get; set; }//每頁大小 //頁數列表,此列表中不包含第一頁和最后一頁 public List<int> pagelist { get; set; } public List<int> getPagelist() { var p = new List<int>(); if (totalPages <= showPageNum)//全部顯示 { for (int i = 2; i < totalPages; i++) { p.Add(i); } } else { var yiban = ((int)((showPageNum + 1) / 2)) - 1;//前后保留頁數大小 if (curPage - yiban > 1 && curPage + yiban < totalPages) { //兩頭都可取值 this.previousSpot = this.nextSpot = true; for (int i = curPage - yiban+1; i < curPage + yiban; i++) { p.Add(i); } } else if (curPage - yiban > 1 ) { //右頭值少 this.previousSpot = true; for (int i = totalPages - 1; i > totalPages - showPageNum + 2; i--) { p.Add(i); } } else if (curPage - yiban <= 1 ) { //左頭值少 this.nextSpot = true; for (int i = 2; i < showPageNum; i++) { p.Add(i); } } } return p.OrderBy(x => x).ToList(); }
這里默認設定了顯示頁碼時最多顯示的頁碼數量為9,也就是頁碼數量超過9時,用...隱藏其超過的數,當前頁始終顯示在最中央。
2、后台提取數據的控制器:
int pagesize = 10;//設定每頁顯示的記錄數量 //取 public ActionResult GetData(int curPage = 1) { var total = db.news.Count();//取記錄數 var pages = new PageList(curPage, total, pagesize);//初始化分頁類 var list = db.news.OrderBy(x => x.id).Skip((curPage - 1) * pagesize).Take(pagesize);//取頁面記錄列表 var data = new { list = list, pages = pages };//構造對象 return Json(data, JsonRequestBehavior.AllowGet); }
頁面中的數據是通過異步方式提取,第一次是默認是第一頁,這里的頁面記錄列表的提取使用了EF,當然還可以使用其它方式訪問數據庫,這里只是為了方便演示,建議在真正項目使用更加高效的方法。
這里提供dapper訪問的方法,其中加入了查詢語句。
public ActionResult getdata(news info, int page = 1) { var conn = db.Database.Connection; var sql = string.Format("select * ,row_number() over ( order by id desc ) as rownum from news where 1=1 "); if (!string.IsNullOrEmpty(info.title)) { sql = string.Format(sql + " and title like '%{0}%'", info.title); } if (!string.IsNullOrEmpty(info.writer)) { sql = string.Format(sql + " and writer like '%{0}%'", info.writer); } if (!string.IsNullOrEmpty(info.depname)) { sql = string.Format(sql + " and depname ='{0}'", info.depname); } var sql2 = string.Format("select top {0} * from (" + sql + ") as a where a.rownum>({1}-1)*{0} and a.rownum<={0}*{1}", pagesize, page); var sqlcount = string.Format("select count(rownum) from (" + sql + ")"); using (conn) { var list = conn.Query<news>(sql2); var total = conn.QuerySingle<int>("select count(id) from (" + sql + ") as aa"); var pages = new PageList(page, pagesize, total); var obj = new { list = list, pages = pages }; return Json(obj, JsonRequestBehavior.AllowGet); } }
3、頁面中的分頁實現如下:
@{ ViewBag.Title = "Index"; } <link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/css/font-awesome.min.css" rel="stylesheet" /> <script src="~/Content/js/jquery-1.8.2.min.js"></script> <script src="~/Content/js/bootstrap.min.js"></script> <script src="~/Scripts/vue.min.js"> </script> <script src="~/Scripts/axios.min.js"></script> <hr> <div id="app"> <ul> <li v-for="item in list">{{item.title}}</li> </ul> <nav aria-label="Page navigation"> <ul class="pagination"> <li v-bind:class="{disabled:pages.curPage==1}"> <a href="javascript:;" v-on:click="pages.curPage==1?'':go(pages.curPage-1)" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li v-bind:class="{active:pages.curPage==1}"><a href="javascript:;" v-on:click="go(1)">{{pages.firstNum}}</a></li> <li v-if="pages.previousSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-for="item in pages.pagelist" v-bind:class="{active:pages.curPage==item}"><a href="javascript:;" v-on:click="go(item)">{{item}}</a></li> <li v-show="pages.nextSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-bind:class="{active:pages.curPage==pages.lastNum}"><a href="javascript:;" v-on:click="go(pages.lastNum)">{{pages.lastNum}}</a></li> <li v-bind:class="{disabled:pages.curPage==pages.lastNum}"> <a href="javascript:;" v-on:click="pages.curPage==pages.lastNum?'':go(pages.curPage+1)" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', data:{ list: [], pages:[], }, mounted: function () { this.getData(); }, methods: { go: function (n) { this.getData(n); }, getData: function (n) { var _this = this; axios.post("/home/getData", { curPage: n }).then(function (res) { _this.pages = res.data.pages; _this.list = res.data.list; }); } } }); </script>
分頁部分已經通過改造,使用了Vue的方式,使用時直接復制即可使用,使用的方法就有兩個go,getData,每次在使用時可以在方法中加入這兩個方法, ajax使用axios.js實現 。
簡單寫成組件,以后再完善
@{ ViewBag.Title = "Index"; } <link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/css/font-awesome.min.css" rel="stylesheet" /> <script src="~/Content/js/jquery-1.8.2.min.js"></script> <script src="~/Content/js/bootstrap.min.js"></script> <script src="~/Scripts/vue.min.js"> </script> <script src="~/Scripts/axios.min.js"></script> <hr> <div id="app"> <ul> <li v-for="item in list">{{item.title}}</li> </ul> <mypage v-bind:pages="pages" v-on:getdata="getData"></mypage> </div> <template id="myPage"> <nav aria-label="Page navigation"> <ul class="pagination"> <li v-bind:class="{disabled:pages.curPage==1}"> <a href="javascript:;" v-on:click="pages.curPage==1?'':go(pages.curPage-1)" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li v-bind:class="{active:pages.curPage==1}"><a href="javascript:;" v-on:click="go(1)">{{pages.firstNum}}</a></li> <li v-if="pages.previousSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-for="item in pages.pagelist" v-bind:class="{active:pages.curPage==item}"><a href="javascript:;" v-on:click="go(item)">{{item}}</a></li> <li v-show="pages.nextSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-bind:class="{active:pages.curPage==pages.lastNum}"><a href="javascript:;" v-on:click="go(pages.lastNum)">{{pages.lastNum}}</a></li> <li v-bind:class="{disabled:pages.curPage==pages.lastNum}"> <a href="javascript:;" v-on:click="pages.curPage==pages.lastNum?'':go(pages.curPage+1)" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </template> <script type="text/javascript"> Vue.component('mypage', { template: '#myPage', props: ['pages'], methods: { go: function (n) { this.$emit("getdata", n=n); }, } }); var app = new Vue({ el: '#app', data:{ list: [], pages:[], }, mounted: function () { this.getData(); }, methods: { go: function (n) { this.getData(n); }, getData: function (n) { n = n || 1; var _this = this; axios.post("/home/getData", { curPage: n }).then(function (res) { _this.pages = res.data.pages; _this.list = res.data.list; }); } } }); </script>
進一步改進組件,通用性更好,下面把訪問地址等提取到組件中
@{ ViewBag.Title = "Index"; } <link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/css/font-awesome.min.css" rel="stylesheet" /> <script src="~/Content/js/jquery-1.8.2.min.js"></script> <script src="~/Content/js/bootstrap.min.js"></script> <script src="~/Scripts/vue.min.js"> </script> <script src="~/Scripts/axios.min.js"></script> <hr> <div id="app"> <ul> <li v-for="item in list">{{item.title}}</li> </ul> <mypage v-on:getdata="getdata" url="/home/getdata"></mypage> </div> <template id="myPage"> <nav aria-label="Page navigation"> <ul class="pagination"> <li v-bind:class="{disabled:pages.curPage==1}"> <a href="javascript:;" v-on:click="pages.curPage==1?'':go(pages.curPage-1)" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li v-bind:class="{active:pages.curPage==1}"><a href="javascript:;" v-on:click="go(1)">{{pages.firstNum}}</a></li> <li v-if="pages.previousSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-for="item in pages.pagelist" v-bind:class="{active:pages.curPage==item}"><a href="javascript:;" v-on:click="go(item)">{{item}}</a></li> <li v-show="pages.nextSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-bind:class="{active:pages.curPage==pages.lastNum}"><a href="javascript:;" v-on:click="go(pages.lastNum)">{{pages.lastNum}}</a></li> <li v-bind:class="{disabled:pages.curPage==pages.lastNum}"> <a href="javascript:;" v-on:click="pages.curPage==pages.lastNum?'':go(pages.curPage+1)" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </template> <script type="text/javascript"> Vue.component('mypage', { template: '#myPage', props: ['url'], data:function(){ return { pages: [], } }, mounted: function () { this.go(1); }, methods: { go: function (n) { this.getData(n); }, getdata: function (n) { var me = this; axios.post(this.url, { curPage: n }).then(function (res) { me.pages = res.data.pages; me.$emit("getdata", res.data.list); }); } } }); var app = new Vue({ el: '#app', data: { list: [], }, methods: { getData: function (data) { this.list = data; } } }); </script>
為了以后能重用,可以把組件放在一個頁面中,其它地方法引用組件。在.netMVC4下封裝此分頁實現如下 :
分頁實現
1、自定義一個分頁類:WzhPaged,封裝分頁各參數
public class WzhPaged { /// <summary> /// 初始化 /// </summary> /// <param name="curPage">當前頁</param> /// <param name="total">記錄數</param> /// <param name="pagesize">每頁顯示的記錄數</param> /// <param name="showPageNum">頁碼顯示數量</param> public WzhPaged(int curPage, int total, int pagesize = 10, int showPageNum = 9) { this.total = total; this.pagesize = pagesize; this.curPage = curPage; this.showPageNum = showPageNum; this.firstNum = 1; this.lastNum = this.totalPages; this.pagelist = this.getPagelist(); } //前面的點,前面省略的頁數用.來代表, public bool previousSpot { get; set; } //后面的點,后面省略的頁數用.來代表, public bool nextSpot { get; set; } //第一個頁數,一般都是1 public int firstNum { get; set; } //最后一個頁數,也就是最大頁數 public int lastNum { get; set; } //默認頁面顯示最多頁號數目 public int showPageNum { get; set; } public int total { get; set; }//總記錄數 //總頁數 public int totalPages { get { return (int)Math.Ceiling((double)total / pagesize); } } public int curPage { get; set; }//當前頁 public int pagesize { get; set; }//每頁大小 //頁數列表,此列表中不包含第一頁和最后一頁 public List<int> pagelist { get; set; } public List<int> getPagelist() { var p = new List<int>(); if (totalPages <= showPageNum)//全部顯示 { for (int i = 2; i < totalPages; i++) { p.Add(i); } } else { var yiban = ((int)((showPageNum + 1) / 2)) - 1;//前后保留頁數大小 if (curPage - yiban > 1 && curPage + yiban < totalPages) { //兩頭都可取值 this.previousSpot = this.nextSpot = true; for (int i = curPage - yiban + 1; i < curPage + yiban; i++) { p.Add(i); } } else if (curPage - yiban > 1) { //右頭值少 this.previousSpot = true; for (int i = totalPages - 1; i > totalPages - showPageNum + 2; i--) { p.Add(i); } } else if (curPage - yiban <= 1) { //左頭值少 this.nextSpot = true; for (int i = 2; i < showPageNum; i++) { p.Add(i); } } } return p.OrderBy(x => x).ToList(); } }
2、使用Vue封裝好分頁代碼單獨放在一個頁面中,比如在Views/Shared下添加頁面 _pagehelper.cshtml:
<template id="mypage"> <nav aria-label="Page navigation"> <ul class="pagination"> <li v-bind:class="{disabled:pages.curPage==1}"> <a href="javascript:;" v-on:click="pages.curPage==1?'':go(pages.curPage-1)" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <li v-bind:class="{active:pages.curPage==1}"><a href="javascript:;" v-on:click="go(1)">{{pages.firstNum}}</a></li> <li v-if="pages.previousSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-for="item in pages.pagelist" v-bind:class="{active:pages.curPage==item}"><a href="javascript:;" v-on:click="go(item)">{{item}}</a></li> <li v-show="pages.nextSpot" class="disabled"><span><span aria-hidden="true">...</span></span></li> <li v-if="pages.lastNum!=1&&pages.lastNum!=0" v-bind:class="{active:pages.curPage==pages.lastNum}"><a href="javascript:;" v-on:click="go(pages.lastNum)">{{pages.lastNum}}</a></li> <li v-bind:class="{disabled:pages.curPage==pages.lastNum}"> <a href="javascript:;" v-on:click="pages.curPage==pages.lastNum?'':go(pages.curPage+1)" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </template> <script type="text/javascript"> Vue.component('mypage', { template: '#mypage', props: ['url', 'prop'], data: function () { return { pages: [], } }, mounted: function () { this.go(1); }, methods: { go: function (n) { this.getdata(n); }, getdata: function (n) { this.prop = this.prop || {}; this.prop.curPage = n; var me = this; axios.post(this.url, this.prop).then(function (res) { me.pages = res.data.pages; me.$emit("getdata", res.data.list); }); } } }); </script>
3、在每個模板頁中引用上面的組件文件,比如模板頁_Layout.cshtml中引用此頁:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
<link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/css/font-awesome.min.css" rel="stylesheet" />
<script src="~/Content/js/jquery-1.8.2.min.js"></script>
<script src="~/Content/js/bootstrap.min.js"></script>
<script src="~/Scripts/vue.min.js"> </script>
<script src="~/Scripts/axios.min.js"></script>
</head>
<body>
@{Html.RenderPartial("_pagehelper");}
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
只要使用了此模板的網頁就有了分頁的組件,就可以方便快捷的使用分頁組件了。
4、下面在需要分頁功能的頁面上使用組裝好的組件,考慮到頁面中可能會使用到查詢功能,所以分兩種情況,無查詢搜索功能和有查詢搜索功能。
(1).無查詢搜索功能,比較簡單一點:
<div id="app"> <ul> <li v-for="item in list">{{item.title}}</li> </ul> <div v-if="list.length==0"> <span> 無數據</span> </div> <mypage v-on:getdata="getData" url="/home/getlistData"></mypage> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { list: [], }, methods: { getData: function (data) { this.list = data; } } }); </script>
<mypage v-on:getdata="getData" url="/home/getlistData"></mypage>, getdata是設置要顯示的列表集合賦值, url是頁面在頁碼間跳轉時獲取數據來源的地址。
(2)有查詢搜索功能,這個較復雜一些,根據自身需求自己來寫查詢條件,這里列出本人在項目使用的方法
<div id="app"> <div class="search"> <input placeholder="標題" style="width:200px;display:inline-block" class="form-control" v-model.trim="title" /> <input placeholder="撰稿人" style="width:200px;display:inline-block" class="form-control" v-model.trim="writer" /> 發部單位:<select v-model="depname" class="form-control" style="width:auto;display:inline"> <option></option> <option v-for="dep in deps">{{dep}}</option> </select> <button class="btn btn-info" v-on:click="btnSearch"><i class="fa fa-search fa-lg"></i> 查詢</button> <button class="btn btn-warning" v-on:click="btnReset"><i class="fa fa-search fa-lg"></i> 重置</button> </div> <div> <table class="table table-responsive"> <tr> <th width="50%">標題</th> <th>時間</th> <th>一級欄目</th> <th>二級欄目</th> <th>發表者</th> <th>單位</th> </tr> <tr v-for="item in list"> <td><a v-bind:href="'/home/news/'+item.id" target="_blank"> {{item.title}}</a></td> <td> {{item.addtime|formatedate}} </td> <td>{{item.colfirstName}}</td> <td>{{item.colsecondName}}</td> <td>{{item.writer}}</td> <td>{{item.depname}}</td> </tr> </table> <div v-if="list.length==0"> <span> 無數據</span> </div> <mypage v-on:getdata="getData" url="/home/getlistData" v-bind:prop="prop" ref="myref" ></mypage> </div> </div> <script> var app = new Vue({ el: '#app', data: { list: [], deps: [], depname: "", title: "", writer: "", curpage: 1, type:'@ViewBag.type' }, filters: { formatedate: function (d) { if (d != "") { var date = new Date(parseInt(d.substring(6, 19))); return date.toLocaleDateString(); } } }, mounted: function () { this.$nextTick(function () { this.loadDep(); }); }, methods: { btnReset: function () { this.depname = this.title = this.writer = ""; }, getData: function (data) { this.list = data; }, btnSearch: function () { this.$refs.myref.go(1); }, loadDep: function () { var _this = this; axios.post("/home/getDepName").then(function (res) { _this.deps = res.data; }); } }, computed: { prop: function () { return { title: this.title, writer: this.writer, depname: this.depname, type: this.type } } }, }); </script>
<mypage v-on:getdata="getData" url="/home/getlistData" v-bind:prop="prop" ref="myref" ></mypage> ,多了兩個屬性, prop是查詢和跳轉時用到的參數,比如查詢姓名等,但這里跳轉的頁碼是不用管,因為我已經在組件中完成它了。
prop要在計算屬性中設置好要傳送的值。
6、.net后台,控制器
不需要查詢的:
public ActionResult getData(int curPage = 1) { var total = db.news.Count();//取記錄數 var pages = new PageList(curPage, total, pagesize);//初始化分頁類 var list = db.news.OrderBy(x => x.id).Skip((curPage - 1) * pagesize).Take(pagesize);//取頁面記錄列表 var obj = new { list = list, pages = pages };//構造對象 return Json(obj, JsonRequestBehavior.AllowGet); }
需要查詢的:
public ActionResult getlistdata(news info, int curPage = 1, string type = "") { var conn = db.Database.Connection; var sql = string.Format("select * ,row_number() over ( order by id desc ) as rownum from news where ispublish=1 and colsecondName='{0}' ", type); if (!string.IsNullOrEmpty(info.title)) { sql = string.Format(sql + " and title like '%{0}%'", info.title); } if (!string.IsNullOrEmpty(info.writer)) { sql = string.Format(sql + " and writer like '%{0}%'", info.writer); } if (!string.IsNullOrEmpty(info.depname)) { sql = string.Format(sql + " and depname ='{0}'", info.depname); } var sql2 = string.Format("select top {0} * from (" + sql + ") as a where a.rownum>({1}-1)*{0} and a.rownum<={0}*{1}", pagesize, curPage); var sqlcount = string.Format("select count(rownum) from (" + sql + ")"); using (conn) { var newslist = conn.Query<news>(sql2); var total = conn.QuerySingle<int>("select count(id) from (" + sql + ") as aa"); var pagelist = new WzhPaged(curPage, total, pagesize); var obj = new { list = newslist, pages = pagelist }; return Json(obj, JsonRequestBehavior.AllowGet); } }
