首页 > 语言 > JavaScript > 正文

Element-UI踩坑之Pagination组件的使用

2024-05-06 15:28:23
字体:
来源:转载
供稿:网友

先说结论:在改变pageSize时,若当前的currentPage超过了最大有效值,就会修改为最大有效值。

一般Pagination组件的声明如下:

<el-pagination  @size-change="handleSizeChange"  @current-change="handleCurrentChange"  :page-size="pageSize"  :current-page="currentPage" :total="total" :page-sizes="[10, 20, 50, 100, 200, 300, 400]"  layout="total, sizes, prev, pager, next, jumper"></el-pagination>

数据都是异步获取的,所以会定义一个获取数据的方法:

getData() { const params = { pageSize: this.pageSize, currentPage: this.currentPage }; get(params).then(res => { if (res.status === 0) { ... this.total = res.result.count; } });}

一般我们会在pageSize或currentPage改变时,再次去获取新数据:

handleSizeChange(val) { this.pageSize = val; this.getData();},handleCurrentChange(val) { this.currentPage = val; this.getData();}

以上都符合常理,看起来没什么问题!但是,来看以下这种特殊情况:

假设有473条数据,即total = 473

当前pageSize = 10, pageCount = Math.ceil(473 / 10) = 48, currentPage = 48

现在将pageSize = 200,则pageCount = Math.ceil(473 / 200) = 3

这时奇怪的事情就发生了,首先页面的表现为:先是无数据,然后过一会数据才加载。

打开控制台查看网络请求,发现获取了两次数据!

查看请求参数,第一次为:pageSize: 200, currentPage : 48

第二次为:pageSize: 200, currentPage: 3

这好像可以解释了,为什么请求了两次数据?因为pageSize与currentPage的改变都会触发事件去请求数据。

但是!pageSize是我们手动改变的,那currentPage呢?

查看整个组件内可能触发currentPage的行为,但并没有。

那只有一种可能,就是Element-UI库内部帮我们修改的!

秉着不求甚解的理念,去查看了Element-UI中Pagination组件的源码:

其中currentPage在Pagination组件内叫 internalCurrentPage

watch: { internalCurrentPage: { immediate: true, handler(newVal, oldVal) { newVal = parseInt(newVal, 10); /* istanbul ignore if */ if (isNaN(newVal)) {  newVal = oldVal || 1; } else {  // 注意这里   newVal = this.getValidCurrentPage(newVal); } if (newVal !== undefined) {  this.internalCurrentPage = newVal;  if (oldVal !== newVal) {  this.$emit('currentPage', newVal);  } } else {  this.$emit('currentPage', newVal); } } }}

注意我注释标明的地方:

newVal = this.getValidCurrentPage(newVal)

方法名getValidCurrentPage,顾名思义 获取有效的当前页

以上两点足以证明,Element-UI中的Pagination组件会修改currentPage为一个有效值!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选