Skip to content

Instantly share code, notes, and snippets.

@0x30
Last active August 25, 2021 11:35
Show Gist options
  • Save 0x30/8b850f24b9452d715f356a2df968183f to your computer and use it in GitHub Desktop.
Save 0x30/8b850f24b9452d715f356a2df968183f to your computer and use it in GitHub Desktop.
/**
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment