之前写过一篇集成IM的文章,后面感觉写的不咋样,重新写一篇
第一步:安装tim-js-sdk
pnpm add tim-js-sdk
为了后续上传文件方便还需要引入上传插件,其他插件看你的情况进行引入
pnpm add tim-upload-plugin
第二步:创建tim服务
在src中创建services文件夹,创建tim.ts文件
// tim.ts
import TIM from "tim-js-sdk";
import TIMUploadPlugin from "tim-upload-plugin";
import { timConfig } from "../config/tim.config";
let tim: any = null;
// 创建 TIM 实例
export function createTIM() {
if (!tim) {
tim = TIM.create({
SDKAppID: timConfig.SDKAppID,
});
tim.setLogLevel(0);
tim.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin });
}
return tim;
}
// 登录 IM
export function loginIM(userID: string, userSig: string) {
if (!tim) {
createTIM();
}
return tim.login({
userID,
userSig,
});
}
// 登出 IM
export function logoutIM() {
if (!tim) {
return Promise.reject("TIM 未初始化");
}
return tim.logout();
}
// 发送消息
export function sendMessage(conversationID: string, text: string) {
if (!tim) {
return Promise.reject("TIM 未初始化");
}
// 创建文本消息
const message = tim.createTextMessage({
to: conversationID,
conversationType: TIM.TYPES.CONV_C2C, // 单聊
payload: {
text: text,
},
});
// 发送消息
return tim.sendMessage(message);
}
// 可选:发送图片消息
export function sendImageMessage(conversationID: string, file: File) {
if (!tim) {
return Promise.reject("TIM 未初始化");
}
const message = tim.createImageMessage({
to: conversationID,
conversationType: TIM.TYPES.CONV_C2C,
payload: {
file,
},
});
return tim.sendMessage(message);
}
// 可选:获取会话列表
export function getConversationList() {
if (!tim) {
return Promise.reject("TIM 未初始化");
}
return tim.getConversationList();
}
// 可选:获取消息列表
export function getMessageList(conversationID: string, count = 15) {
if (!tim) {
return Promise.reject("TIM 未初始化");
}
return tim.getMessageList({
conversationID,
count,
});
}
创建config文件夹,创建tim.config.ts文件
// tim.config.ts
interface TimConfig {
SDKAppID: number
}
export const timConfig: TimConfig = {
SDKAppID: Number(import.meta.env.VITE_IM_SDK_APP_ID)
}
第三步:使用pinia管理IM的状态
在stores文件夹内创建im.ts
// im.ts
import { defineStore } from "pinia";
import { ref, computed } from "vue";
import TIM from "tim-js-sdk";
import { createTIM, loginIM, logoutIM, sendMessage } from "../services/tim";
export const useIMStore = defineStore("im", () => {
const isSDKReady = ref(false);
const isLogin = ref(false);
const currentConversation = ref("");
const conversationList = ref<any[]>([]);
const messageList = ref<Record<string, any[]>>({});
const userInfo = ref<{ userID: string; userSig: string } | null>(null);
// 计算属性
const currentMessages = computed(
() => messageList.value[currentConversation.value] || []
);
// 方法
async function login(userID: string, userSig: string) {
try {
const tim = createTIM();
await loginIM(userID, userSig);
isLogin.value = true;
userInfo.value = { userID, userSig };
tim.on(TIM.EVENT.SDK_READY, handleSDKReady);
tim.on(TIM.EVENT.MESSAGE_RECEIVED, handleMessageReceived);
tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, handleConversationListUpdate);
} catch (error) {
console.error("登录失败:", error);
throw error;
}
}
async function logout() {
try {
await logoutIM();
reset();
} catch (error) {
console.error("登出失败:", error);
throw error;
}
}
function handleSDKReady() {
isSDKReady.value = true;
}
function handleMessageReceived(event: any) {
const messages = event.data;
messages.forEach((message: any) => {
const conversationID = message.conversationID;
if (!messageList.value[conversationID]) {
messageList.value[conversationID] = [];
}
messageList.value[conversationID].push(message);
});
}
function handleConversationListUpdate(event: any) {
conversationList.value = event.data;
}
async function sendInformation(
conversationID: string,
text: string
): Promise<{
data: {
message: any;
};
}> {
try {
const result = await sendMessage(conversationID.replace("C2C", ""), text);
if (!messageList.value[conversationID]) {
messageList.value[conversationID] = [];
}
messageList.value[conversationID].push(result.data.message);
return result;
} catch (error) {
console.error("发送消息失败:", error);
throw error;
}
}
function setCurrentConversation(id: string) {
currentConversation.value = id;
}
function reset() {
isSDKReady.value = false;
isLogin.value = false;
currentConversation.value = "";
conversationList.value = [];
messageList.value = {};
userInfo.value = null;
}
return {
// 状态
isSDKReady,
isLogin,
currentConversation,
conversationList,
messageList,
userInfo,
// 计算属性
currentMessages,
// 方法
login,
logout,
sendInformation,
setCurrentConversation,
reset,
};
});
第四步:创建自己的UI界面,并调用im.ts
<template>
<div class="chat-container">
<!-- 登录表单 -->
<div v-if="!imStore.isLogin" class="login-form">
<input v-model="loginForm.userID" placeholder="请输入用户ID" />
<input v-model="loginForm.userSig" placeholder="请输入UserSig" />
<button @click="handleLogin">登录</button>
</div>
<!-- 聊天界面 -->
<template v-else>
<div class="conversation-list">
<!-- 添加发起新会话按钮 -->
<div class="new-chat">
<input v-model="newChatUserID" placeholder="输入用户ID" />
<button @click="startNewChat">发起会话</button>
</div>
<!-- 现有的会话列表代码 -->
<div v-if="conversationList.length === 0" class="empty-tip">
暂无会话
</div>
<div
v-for="conv in conversationList"
:key="conv.conversationID"
:class="[
'conversation-item',
{ active: conv.conversationID === currentConversation },
]"
@click="setCurrentConversation(conv.conversationID)"
>
<div class="conversation-item">
<div class="conv-avatar">
<!-- 可以使用头像图片或首字母 -->
{{
conv.userProfile?.nick?.[0] ||
conv.userProfile?.userID?.[0] ||
"?"
}}
</div>
<div class="conv-content">
<div class="conv-name">
{{ conv.userProfile?.nick || conv.userProfile?.userID }}
</div>
<div class="conv-last-msg">
{{ conv.lastMessage?.messageForShow }}
</div>
</div>
</div>
</div>
</div>
<div class="chat-area">
<div v-if="!currentConversation" class="empty-tip">请选择会话</div>
<template v-else>
<div class="chat-header">
<div class="chat-title">
{{ getCurrentConversationName }}
</div>
<div class="last-online">last online {{ getLastOnlineTime }}</div>
</div>
<div class="messages" ref="messagesRef">
<div v-if="currentMessages.length === 0" class="empty-tip">
暂无消息
</div>
<div
v-for="msg in currentMessages"
:key="msg.ID"
:class="[
'message',
{ 'message-mine': msg.from === imStore.userInfo?.userID },
]"
>
<div class="message-avatar">
<img :src="getMessageAvatar(msg)" alt="avatar" />
</div>
<div class="message-wrapper">
<div class="message-content">{{ msg.payload?.text }}</div>
<div class="message-time">
{{ new Date(msg.time * 1000).toLocaleString() }}
</div>
</div>
</div>
</div>
<!-- 修改输入区域部分 -->
<div class="input-area">
<input
v-model="inputText"
@keyup.enter="handleSendMessage"
placeholder="Type a message here"
/>
<button class="send-btn" @click="handleSendMessage">
<i class="fas fa-paper-plane"></i>
</button>
</div>
</template>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, nextTick } from "vue";
import { storeToRefs } from "pinia";
import { useIMStore } from "../stores/im";
const imStore = useIMStore();
const inputText = ref("");
const loginForm = ref({
userID: "",
userSig: "",
});
const { currentConversation, conversationList, currentMessages } =
storeToRefs(imStore);
// 登录处理
const handleLogin = async () => {
if (!loginForm.value.userID || !loginForm.value.userSig) {
alert("请输入用户ID和UserSig");
return;
}
try {
await imStore.login(loginForm.value.userID, loginForm.value.userSig);
} catch (error) {
console.error("IM 登录失败:", error);
alert("登录失败,请检查输入是否正确");
}
};
// 监听会话切换
const setCurrentConversation = async (conversationID: string) => {
await imStore.setCurrentConversation(conversationID);
};
const handleSendMessage = async () => {
if (!inputText.value.trim() || !currentConversation.value) return;
try {
await imStore.sendInformation(currentConversation.value, inputText.value);
inputText.value = "";
} catch (error) {
console.error("发送消息失败:", error);
}
};
const newChatUserID = ref("");
// 添加发起新会话方法
const startNewChat = () => {
if (!newChatUserID.value.trim()) {
alert("请输入用户ID");
return;
}
const conversationID = `C2C${newChatUserID.value}`;
setCurrentConversation(conversationID);
newChatUserID.value = "";
};
// 添加新的计算属性
const getCurrentConversationName = computed(() => {
const conv = conversationList.value.find(
(c) => c.conversationID === currentConversation.value
);
return conv?.userProfile?.nick || conv?.userProfile?.userID || "未知用户";
});
const getLastOnlineTime = computed(() => {
const conv = conversationList.value.find(
(c) => c.conversationID === currentConversation.value
);
return "5 hours ago"; // 这里可以根据实际数据计算
});
const getMessageAvatar = (msg: any) => {
return "https://api.dicebear.com/7.x/avataaars/svg?seed=" + msg.from;
};
// 添加消息滚动到底部的逻辑
const messagesRef = ref<HTMLElement | null>(null);
const scrollToBottom = () => {
nextTick(() => {
if (messagesRef.value) {
messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
}
});
};
// 监听消息变化,自动滚动
watch(
currentMessages,
() => {
scrollToBottom();
},
{ deep: true }
);
// 监听会话切换,自动滚动
watch(currentConversation, () => {
scrollToBottom();
});
</script>
<style scoped>
/* 添加登录表单样式 */
.login-form {
width: 300px;
margin: 100px auto;
display: flex;
flex-direction: column;
gap: 16px;
padding: 24px;
border-radius: 8px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.login-form input {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.login-form button {
padding: 8px;
background: #1890ff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.login-form button:hover {
background: #40a9ff;
}
/* 添加新的样式 */
.empty-tip {
text-align: center;
color: #999;
padding: 20px;
}
.conv-name {
font-weight: bold;
margin-bottom: 4px;
}
.conv-last-msg {
font-size: 12px;
color: #666;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.message {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.message-mine {
align-items: flex-end;
}
.message-mine .message-content {
background: #e6f7ff;
}
.message-content {
background: #f5f5f5;
padding: 8px 12px;
border-radius: 4px;
max-width: 80%;
word-break: break-all;
}
.message-time {
font-size: 12px;
color: #999;
margin-top: 4px;
}
.chat-container {
display: flex;
height: 100vh;
background: #f0f2f5;
}
.conversation-list {
width: 300px;
flex-shrink: 0;
background: #fff;
border-right: 1px solid #e6e6e6;
display: flex;
flex-direction: column;
overflow: hidden;
}
.new-chat {
padding: 20px;
background: #fff;
border-bottom: 1px solid #f0f0f0;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.conversation-item {
padding: 16px 20px;
cursor: pointer;
transition: all 0.3s ease;
position: relative;
border-bottom: 1px solid #f0f0f0;
}
.conversation-item:hover {
background: #f5f7fa;
}
.conversation-item.active {
background: #e6f4ff;
}
.conversation-item.active::before {
content: "";
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 3px;
background: #1890ff;
}
.conv-name {
font-size: 15px;
font-weight: 500;
color: #1f2937;
margin-bottom: 6px;
display: flex;
align-items: center;
justify-content: space-between;
}
.conv-last-msg {
font-size: 13px;
color: #6b7280;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
opacity: 0.8;
}
.conversation-item:hover .conv-last-msg {
opacity: 1;
}
.conversation-item.active .conv-name {
color: #1890ff;
}
.conversation-item.active .conv-last-msg {
color: #4096ff;
opacity: 0.8;
}
/* 新增头像样式 */
.conv-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 12px;
background: #f0f2f5;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
color: #1890ff;
}
/* 修改会话项布局 */
.conversation-item {
display: flex;
align-items: center;
}
.conv-content {
flex: 1;
min-width: 0;
}
.new-chat input {
width: 100%;
padding: 8px 12px;
border: 1px solid #e6e6e6;
border-radius: 6px;
margin-bottom: 8px;
transition: all 0.3s;
}
.new-chat input:focus {
border-color: #1890ff;
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}
.new-chat button {
width: 100%;
padding: 8px;
background: #1890ff;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.3s;
}
.chat-area {
flex: 1;
display: flex;
flex-direction: column;
background: #fff;
margin: 16px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.chat-header {
padding: 16px 24px;
border-bottom: 1px solid #e6e6e6;
background: #fff;
}
.chat-title {
font-size: 16px;
font-weight: 600;
color: #1f2937;
}
.last-online {
font-size: 12px;
color: #6b7280;
margin-top: 4px;
}
.messages {
flex: 1;
padding: 24px;
overflow-y: auto;
background: #fff;
}
.message {
display: flex;
gap: 12px;
margin-bottom: 20px;
align-items: flex-start;
}
.message-mine {
flex-direction: row-reverse;
}
.message-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
overflow: hidden;
flex-shrink: 0;
}
.message-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.message-content {
padding: 12px 16px;
border-radius: 12px;
max-width: 60%;
background: #f2f3f5;
position: relative;
font-size: 14px;
line-height: 1.5;
}
.message-mine .message-content {
background: #1890ff;
color: #fff;
}
.input-area {
padding: 16px 24px;
border-top: 1px solid #e6e6e6;
background: #fff;
display: flex;
align-items: center;
gap: 12px;
}
.input-area input {
flex: 1;
padding: 10px 16px;
border: 1px solid #e6e6e6;
border-radius: 24px;
transition: all 0.3s;
}
.input-area input:focus {
outline: none;
border-color: #1890ff;
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}
.send-btn {
width: 36px;
height: 36px;
border-radius: 50%;
background: #1890ff;
color: #fff;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s;
}
.send-btn:hover {
background: #40a9ff;
transform: scale(1.05);
}
/* 优化滚动条 */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #d1d5db;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #9ca3af;
}
</style>
第五步:美化属于自己的样式,增加更多的功能细节
到这一步你就集成好了IM服务