vue單頁面如何在後退時返回到上次滾動位置

第一種方法、在main.js裏面,此時模式mode要爲 history,頁面需要設置

<keep-alive ><router-view v-if="$route.meta.keepAlive"></router-view></keep-alive> 做緩存


const router = new VueRouter({
  mode: 'history',
  routes,
    //滾動到原來位置的方法
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      if (from.meta.keepAlive) {
        from.meta.savedPosition = document.body.scrollTop
      }
      return { x: 0, y: to.meta.savedPosition || 0 }
    }
  }
})

第二種方法、在所需要實現的頁面中加入

mounted() {
    window.CateListScrollTop = 0;
  },
beforeRouteLeave (to, from, next) {
//離開該頁面的時候把高度記錄
    window.CateListScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    next()
  },
  activated() { 
//返回的時候滾動到記錄的高度
//延時200ms,不延遲滾動的話,有商品頁內容高度比較小的情況就返不回原來的位置
    setTimeout(() => {
      window.scrollTo(0, window.CateListScrollTop);
    }, 200);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章