Akryum / vue-virtual-scroller

⚡️ Blazing fast scrolling for any amount of data
https://vue-virtual-scroller-demo.netlify.app
9.46k stars 901 forks source link

Keep scroll position when adding items at the top #728

Open Vissie2 opened 2 years ago

Vissie2 commented 2 years ago

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.

mirkos93 commented 2 years ago

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

dragos-boisteanu commented 2 years ago

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