Vue:分頁練習(ajax demo資料)
by cactus77kiki
HTML
<!--try:vue pager-->
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>-->
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="app">
<table class="table table-condensed">
<tr>
<th>#</th>
<th>userid</th>
<th>id</th>
<th>title </th>
</tr>
<tr v-for="(r, index) in rows.slice(pageStart, pageStart + countOfPage)">
<td>{{ (currPage-1) * countOfPage + index + 1 }}</td>
<td>{{ r.userid }}</td>
<td>{{ r.id }}</td>
<td>{{ r.title }}</td>
</tr>
</table>
<div class="pagination">
<ul>
<li v-bind:class="{'disabled': (currPage === 1)}"
@click.prevent="setPage(currPage-1)"><a href="#">Prev</a></li>
<li v-for="n in totalPage"
v-bind:class="{'active': (currPage === (n))}"
@click.prevent="setPage(n)"><a href="#">{{n}}</a></li>
<li v-bind:class="{'disabled': (currPage === totalPage)}"
@click.prevent="setPage(currPage+1)"><a href="#">Next</a></li>
</ul>
</div>
<!--<div>Filter: <input type="text" v-model="filter_name"></div>-->
</div>
</body>
</html>
JavaScript
/*Vue.filter('recordLength', function (result, key) {
this.$set(key, result.length);
return result;
});*/
var app = new Vue({
el: '#app',
data: {
rows: [],
countOfPage: 5, //每頁資料筆數
currPage: 2 //目前頁碼
//filter_name: '',
//filteredRowCount: null
},
computed: {
pageStart: function(){
return (this.currPage - 1) * this.countOfPage;
},
totalPage: function(){ //總頁數
return Math.ceil(this.rows.length / this.countOfPage);
}
},
methods: {
setPage: function(idx){
if( idx <= 0 || idx > this.totalPage ){
return;
}
this.currPage = idx;
},
},
created: function(){
var self = this;
let url = 'https://jsonplaceholder.typicode.com/posts';
//'https://www.json-generator.com/api/json/get/cknklDscqG?indent=2'
$.get(url, function(data){
self.rows = data;
//console.log(data);
});
}
});