uniapp开发——h5版本页面切换无法重置页面滚动状态的处理方案

前言:

使用vue开发h5的时候,都会使用vue-router的scrollBehavior函数处理页面滚动状态,代码如下:

const router = new VueRouter({
  mode: "hash",
  routes,
  scrollBehavior(to, from, savePosition) {
    if (savePosition && to.meta.keepAlive) {
      return savePosition;
    }
    return {
      x: 0,
      y: 0
    }
  }
});

但是uniapp有自己的路由,且不支持vue-router,纵使有不少诸如uni app 路由库 uni-simple-router | uni-simple-router (hhyang.cn)之类的插件,但使用起来也是比较麻烦的,而且有些高级功能还要收费,所以,非必须就不建议使用了。

对于已经滚动了的页面切换到下一个页面保留了一定的滚动,这个问题直接使用uni.pageScrollTo()就可以了,可以封装成公共函数,需要使用到的页面直接引用,代码如下:

public.js

//h5页面初始化,页面切换默认不会重置滚动状态,需要在OnReady生命周期中处理
function initPageScroll() {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 0
  });
}
export {
  initPageScroll
}

demo.vue

onReady() {
    $my.initPageScroll();
}

注意,一定要在onReady生命周期中调用,如果在onLoad中调用,则会出现滚动到顶部的过渡效果,即使把uni.pageScrollTo()的duration设置为0也没用。

posted on 2024-01-18 10:39  逍遥云天  阅读(34)  评论(0编辑  收藏  举报

导航