Skip to content
Advertisement

VueJS – How to scroll bottom when data changes

In my component, I got a messages array.

data: function () {
        return {
            messages: [],
            first_load: false
            ...
        }

This messages array get initially populated with an Ajax call after the creation of my component. After the data comes from the server I just push it into my messages variable, it paints all messages in the UI amazingly but after it gets pushed I try to scroll bottom my UI so the user watches only the latest content.

data.body.data.messages.map((message) => {
    this.messages.push(message)
}
this.scroll_bottom()

I noticed that performing a simple javascript scroll bottom line just after pushing my data won’t work as the UI gets refreshed asynchronously (When i .push to my array it won’t execute next line before syncing the UI), so I ended up adding a timeout and then scrolling bottom, but this is super shameful I think.

My hack:

watch: {
    messages:{
        handler: function (val, oldVal) {
            if (!this.first_load) {
                this.first_load = true
                setTimeout(() => {
                    this.scroll_bottom()
                }, 1000);
            }
        },
        deep: true
    }
}

Any ideas on how to leverage this? Thanks!

Advertisement

Answer

You can use updated life-cycle hook to do something after a DOM update. Take a look at the official documentation.

updated: function () {
    //scroll down logic here
}

If your updated logic is being called rapidly, you can always use a suitable denouncing method to slow down.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement