HUGE_DICK_10_INCHES's avatar

Scroll down in vue in specific element

I am trying to scroll down on new appeared element in vue:

I have chat messages where I have two arrays:

data() {
  return {
    activeChats: [],
    openedChats: [],
    maxOpened: math.round(window.innerWidth / 300), 
  }
}

When I get new message and the conversation is not in active and opened arrays I add to both and it appears on screen because I used v-for on both arrays.

This everything works but I am not sure how to scroll down on div when new chat appears, I tried using refs but had no luck:

<div class="chat" v-for="chat in openedChats" ref="chat-{chat.id}"></div>

Or even just chat testing with one chat opened..

And inside axios then() after success I said:

this.$refs.chat['-'+response.data.id].scrollTo(9999999,99999999);
or
this.$refs.chat['-'+response.data.id].scrollTop = 99999999;
or
this.$refs.chat.scrollTo(9999999,99999999);
or
this.$refs.chat.scrollTop = 99999999;

And neither worked...

Any help ? :D

Can it be done without additional library, I need no animations just to appear at the bottom of the element...

Something like:

let el = document.getElementById('chat'+response.data.id);
el.scrollTop = el.innerHeight; //or .scrollHeight

Thanks

0 likes
4 replies
click's avatar

If you are not concerned about older browsers take a look at scrollIntoView. https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

It works pretty easy:

// assuming we are in a vue component and you've set a single `ref` key with the name 'chat'

this.$refs.chat.scrollIntoView(); 

A little bit of extra logic could be added to make it "smarter" so it scrolls to the top of or bottom if necessary: https://stackoverflow.com/questions/6215779/scroll-if-element-is-not-visible/33681714#33681714

HUGE_DICK_10_INCHES's avatar

I passed ID into id of element and used:

let a = document.getelementbyid('chat-'+id);

a.scrollTop = a.scrollHeight;

And it works like it should.

@D9705996 btw I have another problem and it is with vue.set for changing object. It works only if I change data root value as object but if I change object within that data root object it does change but reactivity doesnt work.... It is for opened chats on screen...

sfz0311's avatar

If you look at Vue api, and search $ref. You will find that the way you are doing here will return a html node, not element.

<!-- vm.$refs.p will be the DOM node -->
<p ref="p">hello</p>

<!-- vm.$refs.child will be the child component instance -->
<child-component ref="child"></child-component>

Therefore, scrollTop not working here, since scrollTop works for html element not node.

Please or to participate in this conversation.