Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep scroll position when returning to page

Tags:

nuxt.js

I have a long list on page A that I am scrolling through. When I visit another page and later return to page A, I want to be at the scroll position where I left.

I have found this package for Vue (https://github.com/jeneser/vue-scroll-behavior), but I can't get it to work with NuxtJS.

Any advice or ideas on how I best approach this?

like image 865
Sebastian Avatar asked Aug 17 '18 02:08

Sebastian


Video Answer


2 Answers

/**
 use:
 ```js
  import router from "<you router path>"
  import KeepScroll from "<you code path>"
  Vue.use(KeepScroll, { router })
 ```
and set `keep-scroll-postion` u need save scroll position.
```html
<div v-keep-scroll-postion>
... more
... more
... more
... more
</div>
```
 */

import Router from 'vue-router';
import Vue, { PluginObject } from "vue"

/// keep-alive-scroll-postion-value
const AttributeParamName = "k-l-s-p-v"

/// create custom directive to save scroll position
const configureCustomDirective = () => {
  Vue.directive("keep-scroll-postion", {
    bind: function (el) {
      el.addEventListener("scroll", (event) => {
        const target = event.target as HTMLElement
        if (target === undefined) return
        target.setAttribute(AttributeParamName, target.scrollLeft + '-' + target.scrollTop);
      })
    }
  })
}

interface VueKeepScrollPositionPlugin {
  router: Router
}

const VueKeepScrollPositionPlugin: PluginObject<VueKeepScrollPositionPlugin> = {
  install(vue, option) {
    if (option?.router === undefined) return
    configureCustomDirective()
    const findAndConfigScrollPostion = () => {
      document.querySelectorAll(`[${AttributeParamName}]`).forEach(element => {
        const offset = element.getAttribute(AttributeParamName)?.split("-")
        if (offset === undefined) return
        element.scrollTop = Number.parseFloat(offset[1])
        element.scrollLeft = Number.parseFloat(offset[0])
      })
    }
    option?.router.afterEach(() => vue.nextTick(() => findAndConfigScrollPostion()))
  }
}

export default VueKeepScrollPositionPlugin;

maybe this? https://gist.github.com/0x30/8b850f24b9452d715f356a2df968183f

like image 75
zheng Avatar answered Oct 13 '22 15:10

zheng


Sometimes you can simply use $router.go(-1) it keeps scroll position when returning to page.

like image 43
Nan fish Avatar answered Oct 13 '22 16:10

Nan fish