Vue.js讀取本地json檔案並分頁顯示
阿新 • • 發佈:2020-12-25
技術標籤:vue、JQueryvuejscssjavascript
Vue.js讀取本地json檔案並分頁顯示
1.功能實現
通過axios非同步載入技術讀取本地的json檔案內容,並通過vue.js處理資料在h5頁面分頁顯示(這裡以3行資料分頁)
2.student.json資料如下
[
{"stuId":1,"stuName":"李華","stuSex":"男","stuAge":20},
{"stuId":2,"stuName" :"張國偉","stuSex":"男","stuAge":22},
{"stuId":3,"stuName":"劉豔","stuSex":"女","stuAge":19},
{"stuId":4,"stuName":"李小燕","stuSex":"女","stuAge": 22},
{"stuId":5,"stuName":"張鵬","stuSex":"男","stuAge":26},
{"stuId":6,"stuName":"李曄","stuSex":"女","stuAge":20},
{"stuId":7,"stuName":"錢國強","stuSex" :"男","stuAge":21},
{"stuId":8,"stuName":"張三","stuSex":"男","stuAge":22},
{"stuId":9,"stuName":"唐毓民","stuSex":"男","stuAge":25},
{"stuId":10,"stuName":"瑪麗亞","stuSex":"女","stuAge":21},
{"stuId":11,"stuName":"李家明","stuSex":"男","stuAge":21}
]
3.h5程式碼如下
<body>
<div id ="app" v-clack>
<table border="1px" style="width: 400px;" class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th>序號</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
</tr>
</thead>
<tr v-for="student in stuData">
<td>{{ student.stuId }}</td>
<td>{{ student.stuName }}</td>
<td>{{ student.stuSex }}</td>
<td>{{ student.stuAge }}</td>
</tr>
</table>
<!-- 用無序列表做一個頁碼導航條-->
<ul>
<li><a href="#" @click="prePage"> < </a></li>
<li v-for="(value,index) in pageNumber">
<a href="#" @click="thisPage(index)">{{ index+1 }}</a>
</li>
<li><a href="#" @click="nextPage"> > </a></li>
</ul>
</div>
</body>
4.css樣式
<style>
[v-clack]{
display: none;
}
ul{
margin-left: 20px;
}
ul li{
float: left;
list-style: none;
background-color: aqua;
}
ul li a{
text-decoration: none;
padding: 5px 15px;
color:black;
border: 1px solid white;
}
a:hover{
background: tomato;
}
</style>
5.js程式碼
<script>
//建立Vue例項,得到 ViewModel
var app = new Vue({
el: '#app',
data: {
list:[],
pageSize:3,//每頁大小
currentPage:0 //當前頁碼
},/*資料*/
mounted(){
//非同步載入json資料
axios.get('/json/student.json',{}).then(function(response){
app.list=response.data;
});
},/*自動載入函式*/
methods: {
//上一頁
nextPage: function(){
if (this.currentPage == this.pageNumber - 1) return;
this.currentPage++;
},
//下一頁
prePage: function(){
if (this.currentPage == 0) return;
this.currentPage--;
},
//頁碼
thisPage: function(index){
this.currentPage = index;
}
},/*執行觸發函式*/
computed: {
//分頁資料
stuData: function(){
let left = this.currentPage*this.pageSize;
let right = Math.min((this.currentPage+1)*this.pageSize, this.list.length)
return this.list.slice(left, right);//取出一頁資料
},
//共有多少頁
pageNumber: function(){
return Math.ceil(this.list.length / this.pageSize)||1;
}
},/*動態計算屬性*/
});
</script>
6.執行效果