Skip to content

StreamingText 流式文本

逐字显示文本的打字机效果组件,适用于 AI 流式输出场景。

基础用法

通过 text 传入累积文本,组件自动检测追加和重置。

<script setup>
import { ref, onUnmounted } from 'vue'
import StreamingText from '@/vue/components/StreamingText.vue'

const text = ref('')
const fullText = '你好!我是 AI 助手,很高兴为你服务。有什么我可以帮助你的吗?'
let idx = 0
const timer = setInterval(() => {
  idx++
  text.value = fullText.slice(0, idx)
  if (idx >= fullText.length) {
    clearInterval(timer)
  }
}, 80)

onUnmounted(() => clearInterval(timer))
</script>
<template>
  <div style="padding: 12px; border: 1px solid var(--vk-border-color); border-radius: 4px;">
    <StreamingText :text="text" :speed="2" :interval="50" />
  </div>
</template>

不同速度

通过 speed 控制每 tick 显示的字符数。

speed: 1 (默认)

speed: 3

<script setup>
import StreamingText from '@/vue/components/StreamingText.vue'
</script>
<template>
  <div style="display: flex; flex-direction: column; gap: 12px;">
    <div>
      <p style="font-size: 12px; color: var(--vk-text-color-secondary); margin-bottom: 4px;">speed: 1 (默认)</p>
      <StreamingText text="这是速度为1的流式文本效果" :speed="1" :interval="50" />
    </div>
    <div>
      <p style="font-size: 12px; color: var(--vk-text-color-secondary); margin-bottom: 4px;">speed: 3</p>
      <StreamingText text="这是速度为3的流式文本效果" :speed="3" :interval="50" />
    </div>
  </div>
</template>

React 用法

tsx
import { StreamingText } from '@bobocn/element/react'
import '@bobocn/element/style.css'

function App() {
  const [text, setText] = useState('')

  // 模拟流式输出
  useEffect(() => {
    const full = 'Hello, I am an AI assistant.'
    let i = 0
    const timer = setInterval(() => {
      i++
      setText(full.slice(0, i))
      if (i >= full.length) clearInterval(timer)
    }, 80)
    return () => clearInterval(timer)
  }, [])

  return <StreamingText text={text} speed={2} />
}

API

属性 (Attributes)

属性名说明类型默认值
text累积全文string''
speed每 tick 显示字符数number1
interval每 tick 间隔 (ms)number50
showCursor是否显示光标booleantrue
cursorChar光标字符string'│'
cursorStyle光标样式'line' | 'block' | 'underline''line'
paused是否暂停打字动画booleanfalse

方法 (Exposes / Ref)

方法名说明类型
reset重置到初始状态() => void
finish立即完成输出() => void
pause暂停输出动画() => void
resume继续输出动画() => void
isComplete是否已完成输出boolean

基于 MIT 许可发布