分頁組件在項目中經常要用到之前一直都是在網上找些jq的控件來用(逃..),最近幾個項目用上vue了項目又剛好需要一個分頁的功能。於是百度發現幾篇文章介紹的實在方式有點復雜,
沒耐心看自己動手造輪子寫了一個,用vue的計算屬性去實現真正的邏輯代碼大約在20行左右相當好理解現實原理簡單沒什么好介紹的直接上代碼。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue-router</title>
<script src="./vue.js" ></script>
<style>
body{
font-family:"Segoe UI";
}
li{
list-style:none;
}
a{
text-decoration:none;
}
.pagination {
position: relative;
}
.pagination li{
display: inline-block;
margin:0 5px;
}
.pagination li a{
padding:.5rem 1rem;
display:inline-block;
border:1px solid #ddd;
background:#fff;
color:#0E90D2;
}
.pagination li a:hover{
background:#eee;
}
.pagination li.active a{
background:#0E90D2;
color:#fff;
}
</style>
</head>
<body>
<script type="text/x-template" id="page">
<ul class="pagination" >
<li v-show="current != 1" @click="current-- && goto(current)" ><a href="#">上一頁</a></li>
<li v-for="index in pages" @click="goto(index)" :class="{'active':current == index}" :key="index">
<a href="#" >{{index}}</a>
</li>
<li v-show="allpage != current && allpage != 0 " @click="current++ && goto(current++)"><a href="#" >下一頁</a></li>
</ul>
</script>
<div id="app">
<page></page>
</div>
<script>
Vue.component("page",{
template:"#page",
data:function(){
return{
current:1,
showItem:5,
allpage:13
}
},
computed:{
pages:function(){
var pag = [];
if( this.current < this.showItem ){ //如果當前的激活的項 小於要顯示的條數
//總頁數和要顯示的條數那個大就顯示多少條
var i = Math.min(this.showItem,this.allpage);
while(i){
pag.unshift(i--);
}
}else{ //當前頁數大於顯示頁數了
var middle = this.current - Math.floor(this.showItem / 2 ),//從哪里開始
i = this.showItem;
if( middle > (this.allpage - this.showItem) ){
middle = (this.allpage - this.showItem) + 1
}
while(i--){
pag.push( middle++ );
}
}
return pag
}
},
methods:{
goto:function(index){
if(index == this.current) return;
this.current = index;
//這里可以發送ajax請求
}
}
})
var vm = new Vue({
el:'#app',
})
</script>
</body>
</html>