前提:vue的移动端分页,从列表进入详情后返回后直接回到了当前列表页顶部,而不是回到之前的位置,影响用户体验

解决方案:使用keepalive加上router

具体步骤:router中用meta设置变量scrollTop存储当前的滑动位置,默认为0,导航守卫中给其赋值,然后在需要的页面中用actived钩子重新给当前页面的scrollTop赋值为meta中记录的scrollTop

代码

router.js

{
        path: 'yourPage',
        name: 'yourPage',
        component: () => import('@views/yourPage.vue'),
        meta: {
          title: '我的页面',
          keepAlive: true,
          scrollTop: 0
        }
},
router.beforeEach((to,from,next) => {
  // 记录缓存页之前的位置,从详情页返回后可以直接跳转回当前位置
  if(from.meta.keepAlive) {
    const $content = document.getElementById('app')
    const scrollTop = $content?.scrollTop
    from.meta.scrollTop = scrollTop || 0
  }
  next()
})

yourPage.vue

// 跳转到进入详情页之前的位置
  activated() {
    const $content = document.querySelector('#app')
    $content.scrollTop = this.$route.meta.scrollTop
  },

记得设置keepAlive,否则不起作用

keepAlive相关配置

APP.vue

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

方法二:

yourPage.vue

beforeRouteLeave(to, from, next) {
    //保存滚动条元素div的scrollTop值
    this.scrollY = document.getElementById("app").scrollTop;
    next();
  },
  // 为div元素重新设置保存的scrollTop值
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$nextTick(() => {
        document.getElementById("app").scrollTop = vm.scrollY || 0;
      });
    });
  },

方法三:scrollBehavior

router.js中

const scrollBehavior = function scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition;
  }else {
      return { x: 0, y: 0 }
   }
};
const router = new Router({
  routes,
  scrollBehavior,
});


 

Logo

前往低代码交流专区

更多推荐