Vue 路由跳轉記住滾動位置,返回時回到上次滾動位置

參考:https://blog.csdn.net/qq_40204835/article/details/79853685

方法一: 利用Keep-Alive和監(jiān)聽器

1.首先在路由中引入需要的模塊

{ 
path: ‘/scrollDemo’, 
name: ‘scrollDemo’, 
meta: { 
keepAlive: true // 需要緩存 
}, 
component: resolve => { require([‘../view/scrollDemo.vue’], resolve) } 
}

2.在App.vue中設置緩存組件

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

3.在頁面注冊對應的事件

(1). 在data中定義一個初始值 scroll

(2). 在mouted中 ,mouted中的方法代表dom已經加載完畢

        window.addEventListener('scroll', this.handleScroll);

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

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

       console.log(this.scroll)
     }
  1. activated 為keep-alive加載時調用
      activated() {
          if(this.scroll > 0){
            window.scrollTo(0, this.scroll);
            this.scroll = 0;
            window.addEventListener('scroll', this.handleScroll);
          }
    }

5.deactivated 頁面退出時關閉事件 防止其他頁面出現問題

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

方法二:利用vuex + beforeRouteLeave + watch
main.js中:

var store = new Vuex.Store({
    state: {
        recruitScrollY: 0
    },
    getters: {
        recruitScrollY: state => state.recruitScrollY
    },
    mutations: {
        changeRecruitScrollY(state, recruitScrollY) {
            state.recruitScrollY = recruitScrollY;
        }
    },
    actions: {

    },
    modules: {}
})

組件中(/flashSaleListX為當前組件,即需要記住滾動條位置的組件):

methods:{
      isTabRoute: function() {
            if (this.$route.path === '/flashSaleListX') {
                  let recruitScrollY = this.$store.state.recruitScrollY
                  document.documentElement.scrollTop = recruitScrollY;
            }
      }
},
watch: {
             '$route': 'isTabRoute',
},
beforeRouteLeave(to, from, next) {
      let position = document.documentElement && document.documentElement.scrollTop; //記錄離開頁面時的位置

      if (position == null) position = 0
      this.$store.commit('changeRecruitScrollY', position) //離開路由時把位置存起來
      next()
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容