A
A
Analka2020-02-18 00:12:56
Vue.js
Analka, 2020-02-18 00:12:56

Why is scrolling to the last added element not performed?

Why doesn't scrollTop see the element we just added to the push array? The method is triggered in the Vue component, when a new message has arrived, the scroll goes down to the previous one, that is, the penultimate one.

if (this.dialogSelect > 0){
    window.Echo.private('chat.' + this.dialogSelect)
        .listen('DialogMessage',({data,user_id}) => {
                this.messages.push({
                    avatar: this.userAuth.avatar,
                    fullname: this.userAuth.fullname,
                    user_id: this.userAuth.id,
                    replay: data
                });
            $('.chat--messages__wrapper').scrollTop($('.chat--messages__wrapper').prop('scrollHeight'));
        })
        .listenForWhisper('typing', (e) => {

        });
}


This is how the messages are displayed:

<ul class="chat--messages__wrapper"  v-on:scroll.passive="onScroll">
                                    <li class="chat--messages__item"  v-for="(message,index) in messages">
                                        <a :href="'/profile/'+message.slug" target="_blank" class="chat--user__image" v-bind:style='{ backgroundImage: `url("/storage/${message.avatar}")` }'></a>
                                        <div class="chat--user__data">
                                            <p class="last--massage" v-html="message.replay"></p>
                                        </div>
                                    </li>
                                </ul>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-02-18
@Analka

Because it doesn't exist. The DOM does not update immediately after the data changes. Use nextTick .
And get rid of jquery. Put a ref on the list:

<ul class="chat--messages__wrapper" ref="messages">

And after adding the data, do this:
this.$nextTick(() => {
  const { messages } = this.$refs;
  messages.scrollTop = messages.scrollHeight;
});

A
Andrey Pike, 2020-02-18
@AndyPike

Yes, the DOM cannot change all at once, and reactivity does not work here.
The function should terminate and return to the main thread.
$nextTick or setTimeout(() => {}); , which is the same thing.
Because there is no object for listenForWhisper right now.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question