Vue方法将div滚动到顶部 [英] Vue method scroll div to top
问题描述
我正在学习 vue
.我使用以下方法将聊天消息添加到带有 id="toolbar-chat"
的 div.这个 div 允许在 y 轴上滚动,我希望 div 在每次添加新消息时跳到顶部.为什么我的 JS 不起作用?
I am learning vue
. I have the following method where I add a chat message to a div with id="toolbar-chat"
. This div allows scrolling on y axis and I would like the div to jump to the top every time a new message is added. Why is my JS not working?
document.getElementById("toolbar-chat").scrollTop = 0;
我的vue
方法:
methods: {
addMessage(message) {
this.messages.unshift(message);
document.getElementById("toolbar-chat").scrollTop = 0;
axios.post(chat_send_route, message)
.then(response => {
console.log(response.data);
});
}
}
推荐答案
这是由于 vue 异步更新 dom 造成的.参见Reacivity in depth(Async update Queue)
This is happening due to way vue updates the dom asynchronously. See Reacivity in depth(Async update Queue)
要立即反映更改,请使用
vm.$nextTick(callback)
而不是使用 document.getElementById()
查询 dom 元素,我建议将 ref
属性添加到您的 toolbar-chat
元素并使用 this.$refs
在您的方法中引用它.有关 ref
属性的更多信息,请参阅 docs
instead of querying the dom element using document.getElementById()
I recommend add a ref
attribute to your toolbar-chat
element and reference it in your method using this.$refs
. See docs for more on ref
attribute
<div id="toolbar-chat" ref="toolbarChat"></div>
所以你的方法应该是
methods: {
addMessage(message) {
this.messages.unshift(message);
this.$nextTick(() => {
this.$refs.toolbarChat.scrollTop = 0;
});
axios.post(chat_send_route, message)
.then(response => {
console.log(response.data);
});
}
}
这是有效的fiddle
这篇关于Vue方法将div滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!