Vue 路由跳轉(zhuǎn)記住滾動(dòng)位置,返回時(shí)回到上次滾動(dòng)的位置

這是一個(gè)實(shí)現(xiàn)上拉加載和下拉刷新功能的頁面,這里用了vue-infinite-scroll插件,需要實(shí)現(xiàn)返回頁面時(shí)頁面可以自動(dòng)滑動(dòng)到上次滑動(dòng)的位置。具體實(shí)現(xiàn)方式如下:
1、在App.vue文件中設(shè)置緩存組件keep-alive

<!-- 緩存組件跳轉(zhuǎn)的頁面 -->
 <keep-alive> 
  <router-view v-if="$route.meta.keepAlive" transition-mode="out-in"></router-view>
 </keep-alive>
<!-- 非緩存組件跳轉(zhuǎn)頁面 -->
<router-view v-if="!$route.meta.keepAlive" transition-mode="out-in"></router-view>

2、路由文件中給需要記錄滾動(dòng)位置的頁面設(shè)置keepAlive: true

{
  path: '/Info',
  name: 'InfoList',
  component: InfoList,
  meta: {
    keepAlive: true
  }
}

3、在頁面注冊對應(yīng)的事件
(1)在data中定義一個(gè)初始值 scroll
(2)在mouted中 ,mouted中的方法代表dom已經(jīng)加載完畢

mounted() {
  window.addEventListener('scroll', this.handleScroll)
}

(3)methods 用于存放頁面函數(shù)

handleScroll () {
  this.scroll  = document.documentElement && document.documentElement.scrollTop
  console.log(this.scroll)
}    

4、activated 為keep-alive加載時(shí)調(diào)用

activated() {
  if(this.scroll > 0) {
    window.scrollTo(0, this.scroll); this.scroll = 0;
    window.addEventListener('scroll', this.handleScroll);
  }
}

5、deactivated 頁面退出時(shí)關(guān)閉事件 防止其他頁面出現(xiàn)問題

deactivated(){
  window.removeEventListener('scroll', this.handleScroll);
}

\color{#ea4335}{注意:}keep-alive和上拉加載組件infinite-scroll一起使用時(shí),其他子組件會(huì)觸發(fā)infinite-scroll
\color{#ea4335}{解決方法:}在deactivated里面將屬性infinite-scroll-disabled設(shè)置為true

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容