Scroll to bottom of div with Vue.js

2019-02-04 14:01发布

I have a Vue component with several elements in it. I want to automatically scroll to the bottom of that element when a method in the component is called (basically, do the same as in Scroll to bottom of div?). However, I haven't found the way to get the element within my component and modify scrolTop

I'm currently using Vue 2.0.8

4条回答
Emotional °昔
2楼-- · 2019-02-04 14:42

In the related question you posted, we already have a way to achieve that in plain javascript, so we only need to get the js reference to the dom node we want to scroll.

The ref attribute can be used to declare reference to html elements to make them available in vue's component methods.

Or, if the method in the component is a handler for some UI event, and the target is related to the div you want to scroll in space, you can simply pass in the event object along with your wanted arguments, and do the scroll like scroll(event.target.nextSibling).

查看更多
Anthone
3楼-- · 2019-02-04 14:49

Here is a simple example using #ref to scroll to the bottom of a div.

/*
Defined somewhere:
  var vueContent = new Vue({
      el: '#vue-content',
      ...
 */

var messageDisplay = vueContent.$refs.messageDisplay;
messageDisplay.scrollTop = messageDisplay.scrollHeight;
<div id='vue-content'>
  <div ref='messageDisplay' id='messages'>
    <div v-for="message in messages">
      {{ message }}
    </div>
  </div>
</div>

Notice that by putting ref='messageDisplay' in the HTML, you have access to the element through vueContent.$refs.messageDisplay

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-04 14:50

As I understood, the desired effect you want is to scroll to the end of a list (or scrollable div) when something happens (e.g.: a item is added to the list). If so, you can scroll to the end of a container element (or even the page it self) using only pure Javascript and the VueJS selectors.

var container = this.$el.querySelector("#container");
container.scrollTop = container.scrollHeight;

I've provided a working example in this fiddle: https://jsfiddle.net/my54bhwn

Every time a item is added to the list, the list is scrolled to the end to show the new item.

Hope this help you.

查看更多
Anthone
5楼-- · 2019-02-04 15:01

I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight BUT you have to put this into the updated() hook for the whole solution to work.

data(){
return {
  conversation: [
    {
    }
  ]
 },
mounted(){
 EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
  this.conversation.push(textMsg)
  // Didn't work doing scroll here
 })
},
updated(){              <=== PUT IT HERE !!
  var elem = this.$el
  elem.scrollTop = elem.clientHeight;
},
查看更多
登录 后发表回答