vue-virtual-scroller
vue-virtual-scroller copied to clipboard
Keep scroll position when adding items at the top
Is it possible to keep the scroll position when adding a row at the top of the virtual scroller? I believe this should be default behavior. I've tried calculating the scroll position difference and set it but this results in buggy behavior.
Example: Codesandbox
In the examples folder there is an example just like this but it always scrolls down when adding content which is not viable to my use-case.
I just solved it based on this solution:
export default {
data: () => ({
allRows: [], // Your DynamicScroller items array
previousScrollHeightMinusTop: 0
}),
methods: {
prepareScroll(){
const el = this.$refs.scroller.$el; // $refs.scroller refs to DynamicScroller
this.previousScrollHeightMinusTop = el.scrollHeight - el.scrollTop;
},
restoreScroll(){
const el = this.$refs.scroller.$el; // $refs.scroller refs to DynamicScroller
el.scrollTop = el.scrollHeight - this.previousScrollHeightMinusTop;
},
async yourFetchMethod(){
const rows = [ /* YOUR ROWS TO UNSHIFT */ ];
this.prepareScroll();
for(let i in rows) {
this.allRows.unshift( rows[i] );
await this.$nextTick();
this.restoreScroll()
}
}
}
}
Hope this helps you ✌️
I used these as inspiration to implement it: https://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html https://codesandbox.io/s/silly-greider-j0p8e?file=/src/components/HelloWorld.vue:1316-1324
Maybe they will still be usefull for somebody