SoFunction
Updated on 2025-04-05

How to return to the original scrolling position when vue returns to the previous page

When the project ended, it was found that in the product list on the home page, slide up a few pages and click to enter the details. When returning to the product list from the details page, the page returned to the top. If the test fails, it is said that the user experience is bad. It is required to click from where to return to the original scrolling page when returning to the page.
Idea: Because vue is a single page application, the page will be destroyed when entering other pages. Use keep-alive to prevent it from refreshing. The specific implementation is:

(1). Add:

<template>
 <div >
  <!--<router-view/>-->
  <!--Page returns without refresh-->
  <keep-alive>
   <router-view v-if="$"></router-view>
  </keep-alive>
  <router-view v-if="!$"></router-view>
 </div>
</template>

(2). Page

export default new Router({
 routes: [{
  path: '/',
  name: 'index',
  component: index,
  meta: {
   keepAlive: true
  }
 },

In this way, the mounted side sends only once, and the purpose of returning to the original scrolling position is achieved in the browser. However, when testing on the mobile phone, I found it useless. The solution to achieve the purpose on the mobile phone:

//Record scroll position when the page leavesbeforeRouteLeave (to, from, next) {
   =  || 
  next()
 },
// When entering this page, use the previously saved scroll position to assign the valuebeforeRouteEnter (to, from, next) {
  next(vm => {
    = 
  })
 },

OK! accomplish! !

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.