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?
/**
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
Sometimes you can simply use $router.go(-1)
it keeps scroll position when returning to page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With