vue實現(xiàn)動態(tài)添加數(shù)據(jù)滾動條自動滾動到底部的示例代碼
在使用vue實現(xiàn)聊天頁面的時候,聊天數(shù)據(jù)動態(tài)加到頁面中,需要實現(xiàn)滾動條也自動滾動到底部。這時我找到網(wǎng)上有個插件 vue-chat-scroll
https://www.npmjs.com/package/vue-chat-scroll
但是安裝后發(fā)現(xiàn)是用不了的,報錯信息如下:
VM14383:27 [Vue warn]: Failed to resolve directive: chat-scroll
(found in <Hello>)
這個一直找不到原因,可能是我vue的版本是2.2不支持吧。。。后來找到一個解決辦法:
添加watch方法,監(jiān)聽數(shù)據(jù)變量的變化,動態(tài)添加滾動條,一開始我代碼如下:
watch: {
chatlog() {
var container = this.$el.querySelector("#chatContainer");
console.log(container);
container.scrollTop = container.scrollHeight;
}
}
但是發(fā)現(xiàn)滾動條都是滾動到倒數(shù)第二條數(shù)據(jù)上,所以需要如下代碼來解決:
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;
}
}
相應(yīng)在ul中添加一個id屬性為chatContainer
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue中使用transition和animation的實例代碼
這篇文章主要介紹了詳解vue中使用transition和animation的實例代碼,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

