Two clearings for adding new messages:
1. User interactive sending
2. Customer service sends a message
So we finally encapsulate a function that handles the scroll bar to the bottom
<!-- 聊天主体区域 -->
<div class="chat-list">
<div v-for="(charItem, index) in list" :key="index">
<!-- 左侧是机器人小思 -->
<div class="chat-item left" v-if="charItem.name !== 'me'">
<van-image
fit="cover"
round
src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0kpsqmX61hmZbMXCI-9Edvw7YJYkCX1qtogoRlfCixMNF4dHLkXSKiLVfbMJlXh6z89Q&usqp=CAU"
/>
<div class="chat-pao">{
{ charItem.msg }}</div>
</div>
<!-- 右侧是当前用户 -->
<div class="chat-item right" v-else>
<div class="chat-pao">{
{ charItem.msg }}</div>
<van-image fit="cover" round :src="$store.state.userPhoto" />
</div>
</div>
</div>
methods:{
// 滚动到页面底部
scrollToBottom () {
// 获取到所有的聊天 Item 项
const chatItem = document.querySelectorAll('.chat-item')
// 获取到最后一项对应的 DOM 元素
const lastItem = chatItem[chatItem.length - 1]
// 调用 scrollIntoView() 方法,显示这个元素
lastItem.scrollIntoView({
behavior: 'smooth' // 动画平滑
})
}
}
-
When publishing/receiving a message, call
// 滚动到页面底部(每添加一条消息就让滚动条滚到最底部) // 最后一条消息滚动到屏幕范围 // 数据变化->dom更新是异步的,所以获取到的是上一条div // 解决:vue提供了nextTick/或者settTimeOut方法,可以等待dom节点更新完毕后再执行 this.$nextTick(() => { this.scrollToBottom() })
.chat-list {
height: 100%;
overflow-y: scroll;
}
summary
- Get the native DOM, call the scrollIntoView method, and let the label scroll to the visible window
- If there is no more content below, it will not necessarily roll to the end