路由跳转平滑滚动到顶部&路由回退保持上次位置

277 阅读1分钟
回退保持&平滑滚动,在router文件中
const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) { // 页面回退至上次访问的位置
      return savedPosition
    } else { // 页面刷新,滚动条置顶
      return {
        y: 0,
        behavior: 'smooth'
      }
    }
  }
})
如果顶部有固定导航栏点击跳转页面,要配合下面的方法,否则会经常滚动不到顶部
 methods: {
    //点击顶部固定导航栏click跳转
    //router:跳转的页面,idnex:配合data里的数据显示当前高亮内容
    pageJump(router, index) {
      //如果在当前页面点击的还是当前页面就滚动到顶部
      if (router === this.$route.path) {
        this.scrollSmoothTo(0);
      } else {
        //否则跳转对应页面
        this.$router.push(router);
        this.active = index;
        this.scrollSmoothTo(0);
      }
    },
    
    
    /*下面的方法不用看直接复制到时候调用*/
    //滚动到顶部方法,position:滚动到的高度(0)
    scrollSmoothTo(position) {
      if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function (callback, element) {
          return setTimeout(callback, 17);
        };
      }
      // 当前滚动高度
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 滚动step方法
      let step = function () {
        // 距离目标滚动距离
        let distance = position - scrollTop;
        // 目标滚动位置
        scrollTop = scrollTop + distance / 5;
        if (Math.abs(distance) < 1) {
          window.scrollTo(0, position);
        } else {
          window.scrollTo(0, scrollTop);
          requestAnimationFrame(step);
        }
      };
      step();
    },
  },