zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue实现返回页面时回到原来的位置

Vue 实现 页面 返回 位置 原来 回到
2023-09-11 14:16:33 时间

使用vue中的导航守卫 beforeRouteEnter 与 beforeRouteLeave

  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 回到原来的位置
      const position = JSON.parse(window.sessionStorage.getItem('position'))
      document.querySelector('.list-row').scrollTop = position
    })
  },
  beforeRouteLeave(to, from, next) {
    // 保存离开页面时的位置
    const position = document.querySelector('.list-row').scrollTop
    window.sessionStorage.setItem('position', JSON.stringify(position))
    next()
  }