vue-chat-kit
v0.3.12
Published
一个功能完整的 Vue 3 聊天组件库,支持 WebSocket 实时通信、文件上传、好友管理等功能。独立封装,无需额外 CSS 框架依赖。
Maintainers
Readme
Vue Chat Kit
一个功能完整的 Vue 3 聊天组件库,支持 WebSocket 实时通信、文件上传、好友管理等功能。独立封装,无需额外 CSS 框架依赖!
✨ 特性
- 📦 独立封装 - 所有样式已内置,无需 Tailwind CSS 或其他 CSS 框架
- 🎨 开箱即用 - 完整的聊天界面,样式已打包
- 🔌 WebSocket 实时通信
- 📁 文件上传支持
- 👥 好友管理
- 📝 消息历史记录
- 🔧 高度可配置
- 🔌 完全可定制的 API - 支持自定义适配器来适配你的后端
- 🧩 模块化设计 - 组件本身不是弹窗,可自由嵌入任何位置
🚀 快速开始
安装
npm install vue-chat-kit
# 或
yarn add vue-chat-kit
# 或
pnpm add vue-chat-kit基础使用
<template>
<div>
<!-- ChatPanel 是独立面板,不是弹窗,可以直接嵌入任何位置 -->
<ChatPanel
:config="chatConfig"
@init="onInit"
@message="onMessage"
/>
<!-- 或者你可以自己把它包裹在弹窗里 -->
<el-dialog v-model="showChat" width="1100px">
<ChatPanel :config="chatConfig" />
</el-dialog>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { ChatPanel, createChatConfig } from 'vue-chat-kit'
import 'vue-chat-kit/style'
const showChat = ref(false)
// 配置
const chatConfig = createChatConfig({
// API 基础配置
api: {
baseUrl: 'http://your-api.com',
websocketUrl: 'ws://your-websocket.com'
},
// 用户信息
user: {
username: 'user123',
avatar: 'https://example.com/avatar.jpg'
},
// 模块配置
modules: {
friends: true, // 启用好友模块
apply: true, // 启用好友申请模块
settings: true, // 启用设置模块
fileUpload: true, // 启用文件上传
avatarCrop: true // 启用头像裁剪
}
})
const onInit = () => {
console.log('聊天组件初始化完成')
}
const onMessage = (msg) => {
console.log('收到新消息:', msg)
}
</script>🔌 自定义 API 适配器(推荐)
如果你的后端接口路径不一样,你可以完全自定义 API 实现!
方式 1:使用自定义适配器(最灵活)
<script setup>
import { ChatPanel, createChatConfig } from 'vue-chat-kit'
import 'vue-chat-kit/style'
// 自定义适配器 - 所有接口都在这里定义
const customAdapter = {
// 获取好友列表
async getFriends(currentUser) {
// 你的后端接口调用
const res = await fetch(`/your-api/friends?user=${currentUser}`).then(r => r.json())
return res
},
// 获取聊天历史
async getHistory(fromUser, toUser) {
const res = await fetch(`/your-api/messages?from=${fromUser}&to=${toUser}`).then(r => r.json())
return res
},
// 发送消息(可选 - 如果是通过 WebSocket 发送可以不实现)
// async sendMessage(to, content, type) { ... }
// 标记已读
async setRead(currentUser, friendUser) {
const res = await fetch('/your-api/mark-read', {
method: 'POST',
body: JSON.stringify({ currentUser, friendUser })
}).then(r => r.json())
return res
},
// 上传文件
async uploadFile(file) {
const formData = new FormData()
formData.append('file', file)
const res = await fetch('/your-api/upload', {
method: 'POST',
body: formData
}).then(r => r.json())
return res
},
// ... 其他接口(完整列表见下方)
}
const chatConfig = createChatConfig({
api: {
baseUrl: 'http://your-api.com',
websocketUrl: 'ws://your-websocket.com',
adapter: customAdapter // 使用自定义适配器!
},
user: { username: 'user123' }
})
</script>方式 2:仅修改接口路径
如果你只是想改一下接口路径,可以这样:
const chatConfig = createChatConfig({
api: {
baseUrl: 'http://your-api.com',
websocketUrl: 'ws://your-websocket.com',
endpoints: {
getFriends: '/your-custom-path/friends',
getHistory: '/your-custom-path/messages',
setRead: '/your-custom-path/mark-read',
uploadFile: '/your-custom-path/upload',
addFriend: '/your-custom-path/add-friend',
getApplyList: '/your-custom-path/applications',
agreeFriend: '/your-custom-path/agree',
setChatStatus: '/your-custom-path/chat-status',
getAvailableUsers: '/your-custom-path/available-users',
getUserAvatar: '/your-custom-path/avatar',
uploadAvatar: '/your-custom-path/avatar-upload'
}
},
user: { username: 'user123' }
})📋 完整适配器接口列表
const customAdapter = {
// ==================== 聊天相关 ====================
async getFriends(currentUser) { /* ... */ },
async getHistory(fromUser, toUser) { /* ... */ },
async setRead(currentUser, friendUser) { /* ... */ },
// ==================== 文件相关 ====================
async uploadFile(file) { /* ... */ },
// ==================== 好友相关 ====================
async getAvailableUsers(currentUser) { /* ... */ },
async addFriend(currentUser, friendUser) { /* ... */ },
async getApplyList(currentUser) { /* ... */ },
async agreeFriend(applyUser, friendUser) { /* ... */ },
async setChatStatus(currentUser, friendUser, status) { /* ... */ },
// ==================== 用户相关 ====================
async getUserAvatar(username) { /* ... */ },
async uploadAvatar(file, username) { /* ... */ },
}详细的示例可以参考:adapter-example.js
🎟️ 添加 Token 认证
你可以在配置中添加请求拦截器:
const chatConfig = createChatConfig({
// 方式 1:简单的请求头配置
headers: {
'Authorization': 'Bearer your-token-here'
},
// 方式 2:更强大的请求拦截器(推荐)
requestInterceptors: [
(config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers = {
...config.headers,
'Authorization': `Bearer ${token}`
}
}
return config
}
],
// 响应拦截器
responseInterceptors: [
(response) => {
// 可以在这里处理 401 等响应
return response
}
]
})📖 API 文档
ChatPanel 组件
Props
| 参数 | 说明 | 类型 | 默认值 | |------|------|------|--------| | config | 聊天组件配置对象 | ChatConfig | 必填 |
Events
| 事件名 | 说明 | 回调参数 | |--------|------|----------| | init | 组件初始化完成 | - | | message | 收到新消息 | message | | send | 发送消息 | { text, files } | | error | 错误事件 | error |
createChatConfig 配置项
{
// API 配置
api: {
baseUrl: '',
websocketUrl: '',
// 自定义接口路径(可选)
endpoints: { /* ... */ },
// 自定义 API 适配器(可选,推荐)
adapter: { /* ... */ }
},
// 用户信息
user: {
username: '',
avatar: '',
nickname: '',
email: '',
phone: '',
bio: ''
},
// 模块开关
modules: {
friends: true,
apply: true,
settings: true,
fileUpload: true,
avatarCrop: true
},
// 自定义请求头
headers: {},
// 请求和响应拦截器(可选)
requestInterceptors: [],
responseInterceptors: [],
// WebSocket 配置
websocket: {
maxReconnectAttempts: 5,
reconnectDelay: 3000
}
}🛠️ 开发
cd packages/vue-chat-kit
npm install
npm run example # 运行示例
npm run build # 构建打包📝 发布到 npm
npm run build
npm login
npm publish📄 License
MIT ┌─────────────────────────────────────────────────────────────┐ │ 聊天消息处理流程 │ ├─────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────┐ ┌──────────────────────┐ │ │ │ 首次打开聊天窗口 │ │ WebSocket 收到消息 │ │ │ └──────────┬───────────┘ └──────────┬───────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────────────────────┐ ┌──────────────────────┐ │ │ │ getChatHistory() │ │ push() 到列表尾部 │ │ │ │ (无 minMsgId) │ │ scrollToBottom() │ │ │ └──────────┬───────────┘ └──────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ 渲染到消息列表 │ │ │ │ scrollToBottom() │ │ │ └──────────┬───────────┘ │ │ │ │ │ ┌──────────▼───────────┐ │ │ │ 用户上滑 │ │ │ └──────────┬───────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ getChatHistory( │ │ │ │ minMsgId, ...) │ │ │ └──────────┬───────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ unshift() 到头部 │ │ │ │ 保持滚动位置 │ │ │ └──────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘
