perf: 优化版本

This commit is contained in:
chenchun
2025-12-17 16:50:00 +08:00
parent 28452b4c07
commit 1eca2cb273

View File

@@ -54,7 +54,7 @@
</template>
<script setup lang="ts">
import { ref, nextTick, onMounted, onUnmounted, watch } from 'vue';
import { ref, nextTick, onMounted, onUnmounted } from 'vue';
interface MessageItem {
key?: number;
@@ -81,6 +81,7 @@ const autoScroll = ref(true); // 是否自动滚动到底部
const isUserScrolling = ref(false); // 用户是否正在手动滚动
let scrollTimeout: any = null;
let mutationObserver: MutationObserver | null = null;
let scrollRAF: number | null = null; // 用于存储 requestAnimationFrame ID
/**
* 检查是否滚动到底部
@@ -93,15 +94,29 @@ function isScrolledToBottom(): boolean {
}
/**
* 平滑滚动到底部(不使用 smooth 行为,避免跳动
* 立即滚动到底部(用于内容快速变化时
*/
function scrollToBottomImmediate() {
if (!scrollContainer.value || !autoScroll.value) return;
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
}
/**
* 平滑滚动到底部(使用 RAF 避免过度调用)
*/
function scrollToBottomSmooth() {
if (!scrollContainer.value || !autoScroll.value) return;
requestAnimationFrame(() => {
// 取消之前的 RAF避免重复调用
if (scrollRAF !== null) {
cancelAnimationFrame(scrollRAF);
}
scrollRAF = requestAnimationFrame(() => {
if (scrollContainer.value) {
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
}
scrollRAF = null;
});
}
@@ -159,10 +174,21 @@ function observeContentChanges() {
if (!contentElement) return;
// 创建 MutationObserver 监听内容变化
mutationObserver = new MutationObserver(() => {
mutationObserver = new MutationObserver((mutations) => {
// 如果启用了自动滚动且用户没有在滚动,则滚动到底部
if (autoScroll.value && !isUserScrolling.value) {
scrollToBottomSmooth();
// 检查是否有文本内容变化characterData这通常是 SSE 流式输出
const hasCharacterDataChange = mutations.some(
mutation => mutation.type === 'characterData'
);
if (hasCharacterDataChange) {
// SSE 流式输出时使用立即滚动,避免跳动
scrollToBottomImmediate();
} else {
// 其他情况使用平滑滚动
scrollToBottomSmooth();
}
}
});
@@ -175,20 +201,6 @@ function observeContentChanges() {
});
}
// 监听列表变化
watch(
() => props.list,
() => {
// 列表变化时,如果启用了自动滚动,滚动到底部
if (autoScroll.value) {
nextTick(() => {
scrollToBottomSmooth();
});
}
},
{ deep: true }
);
// 组件挂载时初始化
onMounted(() => {
if (scrollContainer.value) {
@@ -211,6 +223,9 @@ onUnmounted(() => {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
if (scrollRAF !== null) {
cancelAnimationFrame(scrollRAF);
}
if (mutationObserver) {
mutationObserver.disconnect();
}