仔深养生
您的当前位置:首页vue实现动态添加数据滚动条自动滚动到底部的示例代码

vue实现动态添加数据滚动条自动滚动到底部的示例代码

来源:仔深养生


这个一直找不到原因,可能是我vue的版本是2.2不支持吧。。后来找到一个解决办法:

添加watch方法,监听数据变量的变化,动态添加滚动条,一开始我代码如下:

watch: {
 chatlog() {
 var container = this.$el.querySelector("#chatContainer");
 console.log(container);
 container.scrollTop = container.scrollHeight;
 }
 }

但是发现滚动条都是滚动到倒数第二条数据上,所以需要如下代码来解决:

 watch: {
 chatlog() {
 console.log("chatlog change");
 this.$nextTick(() => {
 var container = this.$el.querySelector("#chatContainer");
 console.log(container);
 container.scrollTop = container.scrollHeight;
 })
 // document.getElementById('chatContainer').scrollTop = document.getElementById('chatContainer').scrollHeight+150;

 }
 }

相应在ul中添加一个id属性为chatContainer

显示全文