- 需求:模仿PC企业微信聊天记录,实现向上滚动加载上一页,并处理滚动条位置
1、监听聊天记录的滚动
// <template>
<div class="chat-history" ref="chatHistory" @scroll="handleScroll"></div>
2、添加监听事件
// <script setup>
const chatHistory = ref(null);
const preSrollHeight = ref(0);
const hasMoreHistory = ref(true);
function handleScroll() {
if(hasMoreHistory.value === false) {
return
}
const container = chatHistory.value;
if (container.scrollTop <= 1 ) {
if(refreshing.value) {
return
}
refreshing.value = true;
chatHistoryList()
}
}
3、获取历史消息里面
// 获取历史消息
function chatHistoryList() {
const params = {
userId: userStore.userInfo.web_user_id,
friendId: userStore.userInfo.character_being_used,
seqId: useUserStore.seqId ? useUserStore.seqId : "0",
limit: 20,
token: userStore.token,
header: userStore?.header,
};
getChatHistory(params, (err, response) => {
if (err) {
// 处理错误
ElMessage.error(t('network.failedReceiveHistoryMessage'));
} else {
// 处理成功的响应
// ElMessage({
// showClose: false,
// message: "获取历史消息成功",
// type: "success",
// });
if(response?.chatMessagesList.length == 0) {
hasMoreHistory.value = false
}else {
hasMoreHistory.value = true
}
messages.value.unshift(...response?.chatMessagesList);
formatMessages();
const lastMessage = messages.value[messages.value.length - 1];
topicState(lastMessage);
if (isFirstLoad.value) {
scrollToBottom();
isFirstLoad.value = false;
}
const scrollTop = chatHistory.value.scrollHeight - preSrollHeight.value;
chatHistory.value.scrollTop = scrollTop;
preSrollHeight.value = chatHistory.value.scrollHeight;
nextTick(() => {
let heigh = chatHistory.value.scrollHeight;
let sroll = heigh - preSrollHeight.value;
chatHistory.value.scrollTo(0, sroll);
preSrollHeight.value = heigh;
})}
// 数据加载完成后,设置 refreshing 为 false
refreshing.value = false;
});
}
参考链接