Vue.js结合Element-UI实现分页跳转页面详情返回记住当前点击第几页

该博客讨论了如何在Vue.js应用中利用SessionStorage来保存分页状态。当用户从详情页返回列表页时,通过检查SessionStorage中的detail标识,恢复之前的分页页码。同时,详细介绍了在组件生命周期中如何正确处理数据加载和分页操作,确保在数据变化时分页器能够正确更新。文章还提到了在分页组件上使用v-if条件渲染以防止不必要的重绘。

列表页

mounted

mounted: function() {
    this.showBlogs();
    this.getLastPage()
},

methods

getLastPage() {     //当从详情页返回的时候,先获取详情页中存下来的detall标识,在列表页中,把获取到的分页页码重新赋值赋值,用以返回前的页面,保持不变
    if (sessionStorage.getItem('detail')) {
        // console.log(Number(sessionStorage.getItem("currentPage")));
        //如果有这个就读取缓存里面的数据
        this.currentPage = Number(sessionStorage.getItem("currentPage"));
    } else {
        this.currentPage = 1;
        //这个主要是从其他页面第一次进入列表页,清掉缓存里面的数据
        sessionStorage.removeItem("currentPage");
    }
},
showBlogs() {
    this.$http.get('https://www.guanacossj.com/blog/getallarticle/', {
        _timeout: 5000,
        onTimeout: (request) = >{
            this.$message.error(this.$t('common.timeout'));
            this.loading = false
        }
    }).then((response) = >{
        const res = JSON.parse(response.bodyText);
        if (res.error_num === 0) {
            this.loading = false;
            this.showPagination = true;
            this.blogList = res['list'];
            this.totalItems = this.blogList.length;
            this.handleCurrentChange(this.currentPage)
        } else {
            this.$message.error('查询博客列表失败');
        }
    })
},

在分页的 handleCurrentChange 中,点击切换分页页码,获取当前点击的是第几页:

handleCurrentChange: function(currentPage) {
    this.currentPage = currentPage;
    sessionStorage.setItem('currentPage', currentPage);
},

分页器

一定要通过v-if判断,如果有数据了不要重新渲染。

我们返回当前页面取得总条数totalItems的之前,element-ui的分页组件已经在页面加载完毕,当时的totalItems绑定的是data里面初始化的数据0,所以当总条数为0的时候,分页组件的页码默认为1。并且当totalItems在created生命周期里取得数据后,分页组件也不会刷新。所以这就导致, 页面内容正确,但是页码高亮依旧是第一页。

<el-pagination 
    v-show="showPagination" 
    background="" 
    @size-change="handleSizeChange" 
    @current-change="handleCurrentChange" 
    :current-page.sync="currentPage" 
    :page-sizes="[1, 2, 3, 4]" 
    :page-size="pageSize" 
    :total="totalItems"
    v-if="totalItems !== 0" 
    layout="prev, pager, next, total"> 
</el-pagination>

销毁时

destroyed() {
    sessionStorage.removeItem("detail");
},

详情页

加载数据时加上

sessionStorage.setItem("detail", true);

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值