feat: sse流式对话

master
LCJ-MinYa 10 months ago
parent b6eb8b0756
commit 86ef51c165

@ -68,6 +68,10 @@ const titleArr = [
key: 'virtualList',
title: 'item固定高度的虚拟列表实现',
},
{
key: 'sse',
title: 'ai对话流式显示文本',
},
];
// @/views/demo/**/*.vue

@ -0,0 +1,80 @@
<template>
<base-container>
<h2 class="pt-5 pb-5">流式显示文本(需先启动node-local-server项目作为本地服务端)</h2>
<div>
<el-button
type="primary"
@click="handleSend"
>问个问题</el-button
>
<el-button
type="primary"
@click="handleClose"
>停止</el-button
>
</div>
<div
class="wordbox"
ref="containerRef"
>
<span
id="content"
v-html="content"
></span>
</div>
</base-container>
</template>
<script setup>
import { onMounted, ref, nextTick } from 'vue';
const eventSource = ref(null);
const content = ref('');
const updateContent = (event) => {
console.log(event);
console.log('sse收到消息');
content.value += event.data + '<br/>';
console.log(content.value, 'content内容');
if (event.data === 'End') {
handleClose();
}
nextTick(() => {
// scrollToBottom();
});
};
const handleError = (event) => {
console.log(event);
console.log('sse连接出错');
};
const handleClose = () => {
eventSource.value.close();
};
const containerRef = ref(null);
const scrollToBottom = () => {
containerRef.value.scrollTop = containerRef.value.scrollHeight;
};
const handleSend = () => {
eventSource.value = new EventSource('http://localhost:3000/events');
eventSource.value.addEventListener('message', updateContent);
eventSource.value.addEventListener('error', handleError);
};
onMounted(() => {});
</script>
<style lang="scss" scoped>
.wordbox {
width: 100%;
height: 100%;
overflow: auto;
padding: 20px;
border: 1px solid #ccc;
margin: 20px 0;
border-radius: 5px;
}
</style>
Loading…
Cancel
Save