目錄
項目背景
實現步驟
實現代碼
完整示例代碼
項目背景
chatGPT聊天消息展示滾動面板,每次用戶輸入提問內容或者ai進行流式回答時需要不斷的滾動到底部確保展示最新的消息。
實現步驟
采用element ui 的el-scrollbar作為聊天消息展示組件。
通過操作dom來實現滾動到底部。
通過vue的watch來監聽聊天消息列表的變動。
實現代碼
<el-scrollbar height="400px" ref='scrollMenuRes'><!-- 內容 --></el-scrollbar>
//滾動面板自動滑動到底部
const scrollToBottom = () => {if (scrollMenuRes.value) {const container = scrollMenuRes.value.$el.querySelector('.el-scrollbar__wrap');container.style.scrollBehavior = 'smooth'; // 添加平滑滾動效果container.scrollTop = container.scrollHeight;}
};
完整示例代碼
<template><div><el-scrollbar height="400px" ref='scrollMenuRes'><!-- 內容 --><h1>消息:1</h1><h1>消息:11</h1><h1>消息:111</h1><h1>消息:1111</h1><h1>消息:11111</h1><h1>消息:111111</h1><h1>消息:1111111</h1><h1>消息:11111111</h1><h1>消息:111111111</h1><h1>消息:1111111111</h1><h1>消息:11111111111</h1><h1>消息:111111111111</h1><h1>消息:1111111111111</h1></el-scrollbar></div>
</template><script setup lang="ts">
import { ref,onMounted,watch } from 'vue';
import { ElScrollbar } from 'element-plus';
//聊天消息滾動面板dom
const scrollMenuRes = ref<any>(null);//滾動面板自動滑動到底部
const scrollToBottom = () => {if (scrollMenuRes.value) {const container = scrollMenuRes.value.$el.querySelector('.el-scrollbar__wrap');container.style.scrollBehavior = 'smooth'; // 添加平滑滾動效果container.scrollTop = container.scrollHeight;}
};onMounted(() => {scrollToBottom();
})
</script><style scoped></style>