|
| 1 | +# Page Scroll Position Save and Restore Guide |
| 2 | + |
| 3 | +If you want to save the current scroll position when leaving a page and restore it upon return, you can follow the approach outlined below. |
| 4 | + |
| 5 | +## Basic Approach |
| 6 | + |
| 7 | +1. **Cache the Component**: |
| 8 | + Set `keepAlive` to `true` to cache the component. |
| 9 | + |
| 10 | +2. **Save Scroll Position**: |
| 11 | + Use the `onBeforeRouteLeave` hook to save the current scroll position when leaving the page. |
| 12 | + |
| 13 | +3. **Restore Scroll Position**: |
| 14 | + Use the `onActivated` hook to restore the last saved scroll position when the page is activated. |
| 15 | + |
| 16 | +## Example Code |
| 17 | + |
| 18 | +```js |
| 19 | +// Define a ref to store the scroll position |
| 20 | +const scrollTop = ref(0) |
| 21 | + |
| 22 | +// When a component with keepAlive set to true is activated, scroll to the saved position |
| 23 | +onActivated(() => { |
| 24 | + window.scrollTo(0, scrollTop.value) |
| 25 | +}) |
| 26 | + |
| 27 | +// Before leaving the route, save the current scroll position |
| 28 | +onBeforeRouteLeave(() => { |
| 29 | + scrollTop.value |
| 30 | + = window.scrollY |
| 31 | + || document.documentElement.scrollTop |
| 32 | + || document.body.scrollTop |
| 33 | +}) |
| 34 | +``` |
| 35 | + |
| 36 | +# Handling a Specific Scroll Container |
| 37 | + |
| 38 | +If you need to save and restore the scroll position for a specific element (instead of the entire window), follow these steps: |
| 39 | + |
| 40 | +## 1. Add a ref in the Template |
| 41 | + |
| 42 | +In your template, add a `ref` attribute to the scroll container element. For example: |
| 43 | + |
| 44 | +```html |
| 45 | +<div ref="scrollContainer" class="...">...</div> |
| 46 | + |
| 47 | +``` |
| 48 | + |
| 49 | +## 2. In the setup Function |
| 50 | + |
| 51 | +Use a ref to obtain the element's reference: |
| 52 | + |
| 53 | +```js |
| 54 | +const scrollContainer = ref(null) |
| 55 | +``` |
| 56 | + |
| 57 | +## 3. In the onBeforeRouteLeave Hook |
| 58 | + |
| 59 | +Save the scroll container's scroll position: |
| 60 | + |
| 61 | +```js |
| 62 | +onBeforeRouteLeave(() => { |
| 63 | + if (scrollContainer.value) { |
| 64 | + scrollTop.value = scrollContainer.value.scrollTop |
| 65 | + } |
| 66 | +}) |
| 67 | +``` |
| 68 | + |
| 69 | +## 3. In the onActivated Hook |
| 70 | + |
| 71 | +Restore the scroll container's scroll position: |
| 72 | + |
| 73 | +```js |
| 74 | +onActivated(() => { |
| 75 | + if (scrollContainer.value) { |
| 76 | + scrollContainer.value.scrollTop = scrollTop.value |
| 77 | + } |
| 78 | +}) |
| 79 | +``` |
0 commit comments