vue2.0結(jié)合element-ui實現(xiàn)分頁功能
- 大體結(jié)構(gòu)
<div class="block">
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[10, 20, 30, 40]"http://下拉框可以選擇的,選擇一夜顯示幾條數(shù)據(jù)
:page-size="pagesize"http://當前業(yè)顯示的條數(shù)
layout="prev, pager, next"
:total="len">//這個是總共有多少條數(shù)據(jù)
</el-pagination>
</div>
data() {
return {
articleInfoList: [],//每頁顯示的數(shù)據(jù)
articleList: [],//所有的數(shù)據(jù)
currentPage: 1,//當前頁
len: 0,//默認總的數(shù)據(jù)長度
pagesize: 2,//默認每頁顯示的數(shù)量
};
}
},
methods: {
handleCurrentChange(val) {
console.log(`當前頁: ${val}`);
}
}
方法有兩種隘弊,第一種是處理后臺傳過來的總數(shù)據(jù)哈踱,不需要后臺接口
第二種是后臺寫接口
根據(jù)獲取到的總數(shù)據(jù)處理
created(){
Vue.axios.post('/api/article')
.then(res => {
this.articleList = res.data;
this.len = res.data.length;
this.handleInfo();
})
.catch(err => console.log(err))
},
methods: {
handleInfo() {
// 頁數(shù),如果有小數(shù)梨熙,只取整數(shù)部分
let pageNum = Number(String(this.len / this.pagesize).split(".")[0]);
// 定義一個空數(shù)組
let newArr = [];
// 遍歷獲取的數(shù)據(jù)开镣,每次遍歷都從數(shù)組的0位置開始截取,截取數(shù)量為每頁顯示的數(shù)量
for (let i = 0; i < pageNum; i++) {
newArr.push(this.articleList.splice(0, this.pagesize));
}
// 判斷剩余的數(shù)據(jù)有沒有小于每一頁的數(shù)量咽扇,如果小于邪财,就把剩余的數(shù)據(jù)放進newArr數(shù)組
if (this.articleList.length < this.pagesize) {
newArr.push(this.articleList.splice(0, this.articleList.length));
}
// 將新的數(shù)組賦給articleList[],用來渲染頁面
this.articleList = newArr;
// 第一次進入頁面顯示this.articleList[]數(shù)組的第一個元素
this.articleInfoList = this.articleList[0]
},
currentPageNum(currentPage) {
// currentPage為當前的頁數(shù)
// 顯示當前頁數(shù)對應的數(shù)據(jù)
this.articleInfoList = this.articleList[currentPage - 1];
}
后端寫分頁接口
//獲取文章列表(分頁)
router.post('/articlePage',function(req, res){
var getpageNum = req.body.pageNum;//前臺傳入的參數(shù)
var startPage = parseInt(getpageNum * 10);//每次查找的起始點
var limitNum = '10';//位置偏移,也就是每次需要查詢的條數(shù)
//limit 是重點,
var sql = `SELECT * FROM article_table limit ${startPage},${limitNum}`
db.query(sql,function(err,doc){
if (err) {
console.log('數(shù)據(jù)庫錯誤'+ err)
} else {
res.send(doc).end();
}
})
})
- 前臺
直接渲染每頁的數(shù)據(jù)就好
currentPageNum(val) {
var getpageNum = parseInt(val - 1);
Vue.axios.post('/api/articlePage',{//獲取的是后臺分頁接口
pageNum: getpageNum
})
.then((res)=>{
this.articleInfoList = res.data //返回每頁的數(shù)據(jù)
})
this.currentPage = val;
}