在使用vue實現聊天頁面的時候,聊天數據動態加到頁面中,需要實現滾動條也自動滾動到底部。這時我找到網上有個插件
vue-chat-scroll
https://www.npmjs.com/package/vue-chat-scroll
但是安裝後發現是用不了的,報錯信息如下:
VM14383:27 [Vue warn]: Failed to resolve directive: chat-scroll
(found in <Hello>)
這個一直找不到原因,可能是我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