index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="mock.js"></script>
<script src="myapi.js"></script>
<style>
div {
line-height: 21pt;
}
.line {
border-bottom: solid 1px lightgrey;
padding: 10px
}
.page a {
width: 50px;
margin-left: 5px
}
.page .current {
color: red
}
</style>
</head>
<body>
<div id="root">
<div>
<dl>
<dt>图书列表</dt>
<dd class="page">
<a href="#" :class="i==currentPage?'current':''" @click="currentPage=i" v-for="i in page">第{{i}}页</a>
</dd>
<dd v-for="book in booklist">
{{book.row_index}}、 《{{book.book_name}}》 价格:{{book.book_price}} 出版社:{{book.book_press}}
</dd>
</dl>
</div>
</div>
<script>
const config = {
el: "#root",
data: {
booklist: [],
listsize: 1,
currentPage: 1
},
created(){
this.initBook();
},
beforeUpdate(){
this.initBook();
},
computed: {
page(){ //返回页码
let getPage = Math.ceil(this.listsize / 10);//取整,有小数则+1
if (getPage === 0) getPage = 1;
return getPage;
}
},
methods: {
initBook(){
axios.get("http://mybook.com/book/list?page=" + this.currentPage)
.then((response)=> {
this.booklist = response.data.booklist;
this.listsize = response.data.listsize;//总条数
})
}
},
};
new Vue(config);
</script>
</body>
</html>
myapi.js
const presslist = ['人民邮电出版社', "清华大学出版社", "机械工业出版社", "电子工业出版社"]
const bookData = Mock.mock({
"booklist|50": [
{
"row_index|+1": 1, "book_id|+1": 101, "book_name": "@ctitle", "book_price|50-100.1-2": 0,
"book_press|1": presslist, "book_time": "@date('yyyy-mm-dd')"
}
],
"listsize": 50
});
Mock.mock(new RegExp("http://mybook.com/book/list.*"), "get", (options)=> {
const page = GET("page", options.url, 1), pagesize = GET("pagesize", options.url, 10);
return getDataByPage(page, pagesize, bookData, "booklist")
});
function getDataByPage(page, pagesize, data, key) { //根据页码 页尺寸 来过滤数据
const start = (page - 1) * pagesize;
const end = page * pagesize > data[key].length ? data[key].length : page * pagesize;
let result = [];
for (let i = start; i < end; i++) {
result.push(data[key][i]);// [{book_id},{}]
}
const ret = {};
ret[key] = result;
ret["listsize"] = data.listsize;
return ret;
}
/**
* @return {string}
*/
function GET(paramName, url, defValue) {
const arrObj = url.split("?");
if (arrObj.length > 1) {
const arrPara = arrObj[1].split("&");
let arr;
for (let i = 0; i < arrPara.length; i++) {
arr = arrPara[i].split("=");
if (arr !== null && arr[0] === paramName) {
return arr[1];
}
}
}
return defValue;
}