我們在開發(fā)后臺(tái)管理系統(tǒng)的時(shí)候不可避免的會(huì)遇到列表分頁需求儒士,element 官方盡管已經(jīng)幫我們封裝好了,但是我們每次調(diào)用的時(shí)候依然要傳遞不少參數(shù),看上去很復(fù)雜掰担,為此我們可以以此封裝一個(gè)自己的分頁組件澎胡。
在開發(fā)之前我們需要清除自己需要的參數(shù),我這里用的是這些痹升。
pagination.png
接下來我們就開始正式封裝我們的pagination
組件。
<template>
<div class="pagination">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:page-sizes="[5, 10, 20, 30, 40, 50, 60, 80, 100]"
layout="total, sizes, prev, pager, next, jumper"
:current-page.sync="currentPage"
:page-size="limit"
:total="total"
:small="small">
</el-pagination>
</div>
</template>
<script>
export default {
name: "pagination",
data() {
return {
currentPage: 1
}
},
props: {
// 避免直接改變prop屬性
// 'currentPage': {
// required: false,
// default: 1
// },
'total': {
required: false,
default: 0
},
'limit': {
required: false,
default: 10
},
'small': {
required: false,
type: Boolean,
default: false
}
},
watch: {
currentPage(val) {
// 改變這個(gè)值并不會(huì)觸發(fā) handleCurrentChange
if (typeof val === "number") {
console.log('prop currentPage!!!');
this.currentPage = val;
}
},
},
methods: {
// 當(dāng)前頁變化
handleCurrentChange(val) {
this.$emit("handleCurrentChange", val);
},
// size變化
handleSizeChange(val) {
this.currentPage = 1;
this.$emit('handleSizeChange', val);
},
}
}
</script>
<style scoped>
.pagination {
margin: 20px 0;
text-align: center;
}
</style>
這里有個(gè)小坑畦韭,不要嘗試直接改變currentPage
這個(gè)屬性疼蛾,因?yàn)楫?dāng)你切換分頁的時(shí)候會(huì)觸發(fā)改變prop屬性,改放在data
或computed
中定義廊驼。
errorMessage.png
完成pagination
組件的封裝后,我們可以這樣調(diào)用惋砂,這樣省略了很多參數(shù)看上去簡單多了妒挎。
<template>
<pagination :currentPage="currentPage" :total="total" :limit="limit" :small="true"
@handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange"/>
</template>
<script>
import {invokeApi} from '@/service/api'
import pagination from "@framework/pagination"
export default {
name: "",
components: {
pagination
},
data() {
return {
dataList: [],
currentPage: 1,
limit: 10,
total: 0
}
},
methods: {
getDataList() {
let json = {
limit: this.limit,
page: this.currentPage
};
// 調(diào)用后端接口,這里是封裝過的
invokeApi(json).then(res => {
this.dataList = res.list;
this.total = res.total;
});
},
handleCurrentChange(val) {
this.currentPage = val;
this.getDataList();
},
handleSizeChange(val) {
this.limit = val;
this.currentPage = 1;
this.getDataList();
}
},
created() {
this.getDataList();
}
}
</script>