Vue的scrollBehavior(滚动行为)

很多情况下,用户希望查看详情页以后,返回列表页刚刚浏览的位置

原因:由于列表页组件已经被销毁,所以我们重新返回到列表页后页面会置顶,就需要重新下拉查看列表,这样就做了很多没有必要的操作,也是不符合用户的预期。

大概有3种解决方案:

一、使用vue-router方法scrollBehavior(推荐)

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

二、使用路由守卫(组件内守卫)

原理:在beforRouterLeave的路由钩子记录当前页面滚动位置

//在页面离开时记录滚动位置
beforeRouteLeave (to, from, next) {
    this.scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    next()
  },

//进入该页面时,用之前保存的滚动位置赋值
beforeRouteEnter (to, from, next) {
    next(vm => {
      document.body.scrollTop = vm.scrollTop
    })
  },

三、使用<keep-alive> 缓存

App.vue

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

router.js

 routes: [
    {
      path: '/',
      name: 'List',
      component: () => import('./views/index/list.vue'),
      meta: {
        keepAlive: true // 需要缓存
      }
    },
    {
      path: '/content/:contentId',
      name: 'content',
      component: () => import('./views/index/content.vue'),
      meta: {
        keepAlive: false // 不需要缓存
      }
    },
]

以上就是推荐的常用方法,大家可以参考,不对之处可以指正,一起相互交流,长进技术!!!

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值