Vue項目返回頁面保持上次滾動狀態(tài)方式
更新時間:2025年04月28日 15:37:41 作者:trabecula_hj
這篇文章主要介紹了Vue項目返回頁面保持上次滾動狀態(tài)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Vue項目返回頁面保持上次滾動狀態(tài)
使用背景:
- 首頁-water-collection 當前頁/列表頁-water-collection-list
- 當從列表頁跳轉(zhuǎn)詳情頁面后再返回列表頁面需要保持在上次滾動狀態(tài)
- 每次從首頁進入列表后都要滾動到頂部
一、設(shè)置列表頁keepAlive緩存
{
path: '/water-collection/list',
name: 'water-collection-list',
component: () =>
import('@/views/water-collection/water-list.vue'),
meta: { title: '概要情況',keepAlive:true }
}二、第一次進入列表頁面時在mounted生命周期中監(jiān)聽滾動事件
// mounted
this.$nextTick(() => {
this.tableScorll = this.$refs.tableScorll;
this.tableScorll.addEventListener("scroll", this.handleScroll);
});// 滾動事件,記錄滾動位置并賦值給scrollTop
handleScroll() {
this.scrollTop = this.tableScorll.scrollTop;
},三、第二次之后進入在activated生命周期中監(jiān)聽滾動事件
// activated
this.$nextTick(() => {
this.tableScorll = this.$refs.tableScorll;
this.tableScorll.addEventListener("scroll", this.handleScroll);
});四、beforeRouteEnter判斷是進入頁面還是返回頁面
1. 路由判斷
beforeRouteEnter(to, from, next) {
next((vm) => {
if (from.name === "water-collection") {
vm.isBack = false;
} else {
vm.isBack = true;
}
});
},2. 返回頁面滾動到上次位置,進入頁面則滾動到頂部位置
// activated
if (this.isBack) {
if (this.scrollTop > 0) {
this.tableScorll.scrollTo(0, this.scrollTop);
}
} else {
this.scrollTop = 0;
this.tableScorll&&this.tableScorll.scrollTo(0, 0);
}3. 離開頁面清除滾動事件監(jiān)聽
deactivated() {
this.tableScorll.removeEventListener("scroll", this.handleScroll);
},總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
VuePress在build打包時window?document?is?not?defined問題解決
這篇文章主要為大家介紹了VuePress在build打包時window?document?is?not?defined問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07

