vue-virtual-scroller icon indicating copy to clipboard operation
vue-virtual-scroller copied to clipboard

Keep scroll position when adding items at the top

Open Vissie2 opened this issue 2 years ago • 1 comments

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.

Vissie2 avatar May 17 '22 21:05 Vissie2

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 ✌️

mirkos93 avatar Jun 09 '22 11:06 mirkos93

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

dragos-boisteanu avatar Sep 27 '22 12:09 dragos-boisteanu