Vue返回时记录原来的滚动位置

记录滚动条的位置

这样一个需求,做的管理平台有很多图片,往下面滑动的时候点击某一张图片会进入图片详情页面,返回的时候又回到了最上面,所以这样很麻烦,要做一个返回时还在刚才点击时候的位置。

一、第一种方法

  beforeRouteLeave(to, from, next) {
	//scroll要先在data里面赋值一个0 scroll:0
	//el-main是你这个页面的主体class名称,写你自己的名称。
    this.scroll = document.getElementsByClassName("el-main")[0].scrollTop;
    next();
  },
  activated() {
    // this.getGroupImgList();
    this.$nextTick(() => {
      setTimeout(() => {
        document.getElementsByClassName("el-main")[0].scrollTop = this.scroll;
      }, 0);
    });
  },

二、第二种方法(这种方法有的地方不实用,根据自己的意愿来决定,可以试一下)
1、首先在你最外面的那个div上面用ref

<div
 class="labelListMain-main"
  style="margin-top: 0px"
  ref="wrapper" //定义一个ref
>
......//这就是你里面的内容
</div>

2、方法里面的逻辑

beforeRouteLeave(to, from, next) {
  this.$nextTick(() => {
     this.scroll = this.$refs.wrapper.scrollTop;
   });

   next();
},
activated() {
   this.$nextTick(() => {
     this.$refs.wrapper.scrollTop = this.scroll;
   });
 }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Vue 页面跳转后返回原来位置,可以使用以下两种方法: 1. 使用浏览器的历史记录(history)管理: - 在跳转前,使用 `window.scrollX` 和 `window.scrollY` 获取当前页面的滚动位置,并将其存储在 Vuex 状态管理或浏览器的 localStorage 中。 - 在返回页面,监听路由变化事件,如果返回原来的页面,就使用 `window.scrollTo` 将页面滚动到之前保存的位置。 2. 使用 Vue Router 的 `scrollBehavior` 方法: - 在路由配置中,使用 `scrollBehavior` 方法来自定义路由切换滚动行为。 - 在 `scrollBehavior` 方法中,可以通过 `savedPosition` 参数来获取之前滚动位置,将其作为返回滚动位置。 下面是示例代码: ```javascript // 方法一:使用浏览器的历史记录 // 在跳转前保存滚动位置 window.beforeunload = function() { localStorage.setItem('scrollPosition', JSON.stringify({ x: window.scrollX, y: window.scrollY })); }; // 在返回页面恢复滚动位置 window.onload = function() { const scrollPosition = JSON.parse(localStorage.getItem('scrollPosition')); if (scrollPosition) { window.scrollTo(scrollPosition.x, scrollPosition.y); localStorage.removeItem('scrollPosition'); } }; // 方法二:使用 Vue Router 的 scrollBehavior 方法 const router = new VueRouter({ mode: 'history', routes: [...], scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 }; } } }); ``` 使用以上方法,无论是通过浏览器的历史记录还是通过 Vue Router 的 `scrollBehavior` 方法,都可以实现页面跳转后返回原来位置

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值