在components文件夹中新建分页组件Pagination.vue,代码如下
<template>
<el-row>
<div class="number">
<div>
总共
<span>{{currtotal}}</span> 条记录,每页显示
<span>{{currpageSize}}</span> 条
</div>
</div>
<div class="pag-wrap">
<el-pagination background class="pag" @current-change="pageChange" layout="prev, pager, next" :page-size="currpageSize" :total="currtotal"></el-pagination>
</div>
</el-row>
</template>
<script>
export default {
data() {
return {
currpageIndex: 1, //当前页数
currpageSize: this.pagesize, //每页显示条数
currservicePage: this.options.servicePage, //是否服务端分页
currtotal: 0, //总条数
pagingResult: [], //分页结果
serviceData: [] //服务器请求的数据,用于前端分页,需要首次获取所有服务端数据,进行前端js分页
};
},
props: {
pagesize: {
type: Number,
default: 10
},
options: {
type: Object
}
},
created() {
if (!this.currservicePage) {
this.frontPaging();
}
else {
this.serach();
}
},
methods: {
//分页控件分页事件
pageChange(val) {
if (val) {
this.currpageIndex = val;
}
if (!this.currservicePage) {
this.pagingResult = this.jsPagination(
this.currpageIndex,
this.currpageSize,
this.serviceData
);
this.$emit("getPagingResult", this.pagingResult); //子组件像父组件传值
} else {
this.serach();
}
},
//父组件点击“查询按钮”调用的事件
serach(i) {
if (i) {
this.currpageIndex = 1;
}
if(this.currservicePage){
this.$axios.get(`${this.options.url}&pageIndex=${this.currpageIndex}&PageSize=${this.currpageSize}`).then(res =>
{
this.pagingResult = res.data;
this.currtotal = res.total;
this.$emit("getPagingResult", this.pagingResult); //子组件像父组件传值
});
}else{
this.frontPaging();
}
},
//js分页时,首次获取服务器端所有数据
frontPaging() {
this.$axios.get(this.options.url).then(res => {
this.serviceData = res;
this.currtotal = this.serviceData.length;
this.pageChange(); //调用分页事件
});
},
//前端js分页方法
jsPagination(pageNo, pageSize, array) {
var offset = (pageNo - 1) * pageSize;
return offset + pageSize >= array.length? array.slice(offset, array.length): array.slice(offset, offset + pageSize);
}
}
};
</script>
其他界面调用分页方法,如下:
> 将分页组件放在table下面
<el-input v-model="this.options.serachText" placeholder=""></el-input>
<el-button type="primary" @click="serach()">查询</el-button>
<el-table ref="singleTable" :data="tableData">......</el-table>
<Pagination :options="options" @getPagingResult="getPagingResult"></Pagination>
<script>
import Pagination from "../../components/Pagination";
export default {
data() {
return {
options: {
serachText: ""
servicePage: false, //是否为服务器端分页
url: `/api/User/GetRoleInfoByProjectID?projectId=${localStorage.eleProjectId}` //查询数据源路径,条件可直接跟在后面
},
tableData: [],
}
},
components: {
Pagination
},
methods: {
getPagingResult(result) { //获取子组件向父组件传递的值
this.tableData= result;
this.$refs.singleTable.setCurrentRow(this.tableData[0]); //默认选中第一行
},
serach() {
//调用pagination组件中的serach方法
this.options.url = `/api/User/GetRoleInfoByProjectID?serachText=${this.options.serachText}`
this.$refs.pagination.serach(1); //传入1,指的是显示第一页
},
}
}
</script>