Skip to content

ChatMessage 聊天气泡

AI 聊天场景的消息气泡组件,区分 user/assistant/system 角色,支持头像、时间戳、状态指示和重试。

基础用法

你好,请帮我解释一下什么是 Vue 3 的组合式 API?
03:29
组合式 API 是 Vue 3 引入的一种新的组件编写方式,它允许你使用函数来组织组件逻辑,而不是依赖选项对象。
03:29
<script setup>
import ChatMessage from '@/vue/components/ChatMessage.vue'
</script>
<template>
  <div style="display: flex; flex-direction: column; gap: 8px;">
    <ChatMessage role="user" :timestamp="new Date()">
      你好,请帮我解释一下什么是 Vue 3 的组合式 API?
    </ChatMessage>
    <ChatMessage role="assistant" :timestamp="new Date()">
      组合式 API 是 Vue 3 引入的一种新的组件编写方式,它允许你使用函数来组织组件逻辑,而不是依赖选项对象。
    </ChatMessage>
  </div>
</template>

流式状态

设置 status="streaming" 显示 AI 正在生成的指示器。

解释一下量子计算
03:29
正在思考...
<script setup>
import ChatMessage from '@/vue/components/ChatMessage.vue'
</script>
<template>
  <div style="display: flex; flex-direction: column; gap: 8px;">
    <ChatMessage role="user" :timestamp="new Date()">
      解释一下量子计算
    </ChatMessage>
    <ChatMessage role="assistant" status="streaming" />
  </div>
</template>

错误与重试

设置 status="error" 显示错误信息和重试按钮。

帮我写一段代码
03:29
发送失败
<script setup>
import ChatMessage from '@/vue/components/ChatMessage.vue'

function handleRetry() {
  alert('重试发送')
}
</script>
<template>
  <div style="display: flex; flex-direction: column; gap: 8px;">
    <ChatMessage role="user" :timestamp="new Date()">
      帮我写一段代码
    </ChatMessage>
    <ChatMessage role="assistant" status="error" @retry="handleRetry" />
  </div>
</template>

React 用法

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

function App() {
  return (
    <div>
      <ChatMessage role="user" timestamp={new Date()}>
        Hello!
      </ChatMessage>
      <ChatMessage role="assistant" timestamp={new Date()}>
        Hi, how can I help?
      </ChatMessage>
      <ChatMessage role="assistant" status="error" onRetry={() => console.log('retry')} />
    </div>
  )
}

API

属性 (Attributes)

属性名说明类型默认值
role消息角色(必填)'user' | 'assistant' | 'system'
avatar头像 URLstring
avatarSize头像尺寸'small' | 'default' | 'large''default'
timestamp时间戳string | number | Date
status消息状态'sending' | 'sent' | 'error' | 'streaming''sent'
showAvatar是否显示头像booleantrue
errorMessage错误信息string'发送失败'
retryText重试按钮文案string'重试'
copyable是否显示复制按钮booleanfalse
content可复制的纯文本内容string
copyContent自定义复制内容,优先级高于 contentstring

事件 (Events)

事件名说明回调参数
retry / onRetry点击重试时触发
avatar-error / onAvatarError头像加载失败时触发Event

插槽 (Slots)

插槽名说明
default消息内容

基于 MIT 许可发布