問題場景
列表頁面輸入查詢條件,選擇第3頁,點擊詳情進入詳情頁,從詳情頁返回時,默認列表頁面頁碼重置為1;此時想要緩存該頁碼,有兩種方式;可按業務場景使用
方式一:用vue自帶的 keep-alive組件
官方鏈接:keep-alive
該方式會緩存組件,組件中其他狀態也會被緩存;若只想緩存分頁組件,用方式二。
被緩存的組件生命周期不再有mounted,與之替代的是activated。當被緩存的列表頁面有狀態改變時,可以在activated生命周期中調用更新數據方法;例如從列表頁面對這條數據有一些操作:審批,撤回,明細,修改等。當一條數據點擊審批進入審批頁面並提交審批后返回到列表頁面審批操作需要更新為撤回操作,此時由於頁面被緩存則需要在activated生命周期中調用更新數據方法。
<keep-alive :include="list"> <route-view></route-view> </keep-alive> data(){ return { list:[ 'componesName',//需要緩存頁面組件的name ] } }
activated(){
this.init()
}
方式二:修改分頁組件的 internalCurrentPage
從列表頁進入詳情頁時保存當前選中的頁碼
detail (){ sessionStorage.setItem('currentPage') = this.currentPage }
返回至列表頁時如下,需要注意的是分頁組件本來是 :current-page.sync 我這里去掉了 .sync,不去掉修改internalCurrentPage不生效。
<el-pagination ref="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[100, 200, 300, 400]" :page-size="100" layout="sizes, prev, pager, next" :total="1000"> </el-pagination> //關鍵代碼 mounted(){ this.currentPage = sessionStorage.getItem('currenPage') || 1; }, methods:{ async getList(){ //.....獲取列表數據之后 this.nextTick(() =>{ this.$refs.pagination.internalCurrentPage = this.currentPage
})
}
}
