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);
}

猜你喜欢

转载自blog.csdn.net/qq_38188485/article/details/90343486
今日推荐