Files
chat-demo/src/pages/index/ChatPage.vue
T

1006 lines
22 KiB
Vue

<template>
<div class="chat-page">
<!-- 左侧导航 -->
<aside class="app-sidebar">
<div class="avatar my-avatar">
{{ currentUser.username ? currentUser.username.charAt(0) : "" }}
</div>
<nav class="sidebar-nav" aria-label="功能导航">
<button
class="nav-item"
:class="{ active: activeMenu === 'messages' }"
type="button"
title="消息"
@click="changeMenu('messages')"
>
💬
</button>
<button
class="nav-item"
:class="{ active: activeMenu === 'contacts' }"
type="button"
title="联系人"
@click="changeMenu('contacts')"
>
👥
</button>
<button
class="nav-item"
:class="{ active: activeMenu === 'settings' }"
type="button"
title="设置"
@click="changeMenu('settings')"
>
⚙️
</button>
</nav>
<div class="sidebar-footer">
<button class="nav-item" type="button" title="退出" @click="logout">
↪
</button>
</div>
</aside>
<!-- 左侧联系人 -->
<div class="contact-panel">
<!-- 用户信息 -->
<div class="user-header">
<!-- 用户信息 -->
<div class="my-info">
<div class="my-name">{{ currentUser.username }}</div>
</div>
</div>
<!-- 搜索框 -->
<div class="search-box">
<input v-model="searchText" type="text" placeholder="搜索联系人" />
</div>
<!-- 最近消息列表 -->
<div
class="message-list"
:class="activeMenu === 'messages' ? 'active' : ''"
>
<div
v-for="contact in filteredContacts"
:key="contact.contactName"
class="contact-item"
:class="{
active:
currentContact &&
currentContact.contactName === contact.contactName,
}"
@click="selectContact(contact)"
>
<div class="avatar">
{{ contact.contactName.charAt(0) }}
</div>
<div class="contact-info">
<div class="contact-name">
{{ contact.contactName }}
</div>
<div class="last-message">
{{ contact.content }}
</div>
</div>
<div v-if="contact.unreadCount > 0" class="unread">
{{ contact.unreadCount }}
</div>
</div>
</div>
<!-- 联系人列表 -->
<div
class="message-list"
:class="activeMenu === 'contacts' ? 'active' : ''"
>
<div
v-for="contact in contactList"
:key="contact.contactName"
class="contact-item"
@click="selectContact(contact)"
>
<div class="avatar">
{{ contact.contactName.charAt(0) }}
</div>
<div class="contact-info">
<div class="contact-name">
{{ contact.contactName }}
</div>
</div>
</div>
</div>
</div>
<!-- 右侧聊天区域 -->
<div class="chat-panel">
<!-- 没有选择联系人 -->
<div v-if="!currentContact" class="empty-chat">
<div class="empty-icon">💬</div>
<div>请选择一个联系人开始聊天</div>
</div>
<!-- 当前聊天 -->
<template v-else>
<!-- 聊天顶部 -->
<div class="chat-header">
<div class="avatar">
{{ currentContact.contactName.charAt(0) }}
</div>
<div class="chat-user-info">
<div class="chat-user-name">
{{ currentContact.contactName }}
</div>
<div class="chat-user-status">
{{ currentContact.online ? "在线" : "离线" }}
</div>
</div>
</div>
<!-- 消息区域 -->
<div
ref="messageList"
class="message-list"
:class="activeMenu === 'settings' ? '' : 'active'"
@scroll="handleMessageScroll"
>
<div
v-for="message in contactMessages"
:key="message.id"
class="message-row"
:class="{
'message-me': message.from === 'me',
'message-other': message.from === 'other',
}"
>
<!-- 对方头像 -->
<div v-if="message.from === 'other'" class="avatar message-avatar">
{{ currentContact.contactName.charAt(0) }}
</div>
<div class="message-content">
<div class="message-time">
{{ message.time }}
</div>
<div class="message-bubble">
{{ message.content }}
</div>
</div>
<!-- 我的头像 -->
<div
v-if="message.from === 'me'"
class="avatar message-avatar my-avatar"
>
我
</div>
</div>
</div>
<!-- 输入消息区域 -->
<div
v-if="activeMenu === 'messages' || activeMenu === 'contacts'"
class="input-panel"
>
<div class="toolbar">
<button type="button">😊</button>
<button type="button">📎</button>
</div>
<textarea
v-model="messageText"
placeholder="请输入消息..."
@keydown.enter.exact.prevent="sendMessage"
></textarea>
<div class="send-area">
<span class="enter-tip"> Enter 发送 </span>
<button
class="send-button"
type="button"
:disabled="!messageText.trim()"
@click="sendMessage"
>
发送
</button>
</div>
</div>
</template>
</div>
</div>
</template>
<script>
import {
getUserInfo,
getContactInfo,
getRecentMessages,
getContactMessages,
// sendMessage,
} from "@/utils/api";
import {
connectWebSocket,
sendWebSocketMessage,
closeWebSocket,
// getWebSocket
} from "@/utils/websocket";
export default {
name: "ChatPage",
data() {
return {
// 当前用户
currentUser: {},
// 联系人
contactList: [],
// 当前聊天联系人
currentContact: null,
// 最近聊天列表
recentChats: [],
// 聊天消息
contactMessages: [],
// 首次加载
firstLoad: true,
// 正在加载更多消息
loadingMore: false,
// 是否所有消息都加载完毕
loadEnd: false,
// 搜索联系人
searchText: "",
// 输入的消息内容
messageText: "",
// 当前选中的菜单
activeMenu: "messages",
};
},
computed: {
// 搜索联系人
filteredContacts() {
if (!this.searchText.trim()) {
return this.recentChats;
}
const keyword = this.searchText.trim().toLowerCase();
return this.recentChats.filter((contact) =>
contact.contactName.toLowerCase().includes(keyword)
);
},
},
created() {
this.getCurrentUser();
this.getRecentMessageList();
this.createWebsocket();
},
methods: {
// 切换菜单
changeMenu(menu) {
this.activeMenu = menu;
this.currentContact = null;
if (menu === "contacts") {
this.getContactList();
}
},
// 退出登录
logout() {
// 关闭websocket连接,清除 token 和用户信息
closeWebSocket();
this.$store.commit("SET_TOKEN", "");
this.$store.commit("SET_USERNAME", "");
this.$router.push("/login");
},
// 获取当前登录用户信息
getCurrentUser() {
// 获取当前登录用户信息
getUserInfo()
.then((response) => {
this.currentUser = response.data;
})
.catch((error) => {
console.error(error);
this.$message.error("获取用户信息失败,请重新登录");
this.$router.push("/login");
});
},
// 获取最近消息列表
getRecentMessageList() {
getRecentMessages()
.then((response) => {
this.recentChats = response.data.recentChats || [];
this.selectFirstContact();
})
.catch((error) => {
console.error(error);
this.$message.error("获取消息列表失败");
});
},
// 选择联系人
async selectContact(contact) {
this.currentContact = contact;
this.contactMessages = [];
// 每次选择联系人的时候需要首次加载消息
this.firstLoad = true;
await this.getContactMessageList(contact.contactName, 10, 0);
// 查看联系人后清除未读数量
contact.unreadCount = 0;
// 使用同步等消息获取完成后再让滚动条滚到底部,否则滚动条的位置不对
this.$nextTick(() => {
this.firstLoad = false;
this.scrollToBottom();
});
},
// 选择最近一个联系人
selectFirstContact() {
if (!this.currentContact && this.recentChats.length > 0) {
this.selectContact(this.recentChats[0]);
}
},
// 获取当前联系人的消息列表
async getContactMessageList(contactName, limit, offset) {
try {
// 获取当前联系人的消息列表
const response = await getContactMessages({
contactName: contactName,
limit: limit,
offset: offset,
});
const contactMessages = [];
const messages = response.data.messages || [];
messages.forEach((item) => {
contactMessages.push({
...item,
from:
item.senderName === this.currentUser.username ? "me" : "other",
time: item.time || item.createdAt,
});
});
// 将新获取的消息放到现有消息的最前面,用于按时间顺序倒序展示
this.contactMessages = contactMessages
.reverse()
.concat(this.contactMessages);
console.log("contactMessages", contactMessages);
} catch (error) {
console.error(error);
this.$message.error("获取消息列表失败");
}
},
// 获取联系人列表
getContactList() {
getContactInfo()
.then((response) => {
this.contactList = response.data.contacts.map((contact) => ({
...contact,
unreadCount: contact.unreadCount || 0,
}));
})
.catch((error) => {
console.error(error);
this.$message.error("获取联系人信息失败");
});
},
// 发送消息
sendMessage() {
const content = this.messageText.trim();
if (!content || !this.currentContact) {
return;
}
if (!this.contactMessages[this.currentContact.contactName]) {
this.$set(this.contactMessages, this.currentContact.contactName, []);
}
// 新消息
const newMessage = {
type: "sendMessage",
senderName: this.currentUser.username,
receiverName: this.currentContact.contactName,
content: content,
createdAt: new Date(),
};
try {
sendWebSocketMessage(newMessage);
this.contactMessages.push({
...newMessage,
from: "me",
time: newMessage.createdAt,
});
// 更新最近消息列表
this.updateRecentChat(
"send",
this.currentContact.contactName,
newMessage
);
console.log("contactMessages:" + this.contactMessages);
// 清空输入框
this.messageText = "";
this.$nextTick(() => {
this.scrollToBottom();
});
} catch (error) {
// 清空输入框
this.messageText = "";
console.error(error);
this.$message.error("发送消息失败");
}
},
// 更新最近消息列表
updateRecentChat(messageType, contactName, newMessage) {
const index = this.recentChats.findIndex(
(item) => item.contactName === contactName
);
if (index !== -1) {
//找到这条数据,修改内容并移除后添加到数组最前面
const chat = this.recentChats[index];
chat.content = newMessage.content;
chat.createdAt = newMessage.createdAt;
// 接收非当前正在聊天的联系人新消息时,未读数量 +1
if (
messageType == "receive" &&
this.currentContact.contactName != contactName
) {
chat.unreadCount = (chat.unreadCount || 0) + 1;
}
this.recentChats.splice(index, 1);
this.recentChats.unshift(chat);
console.log(this.recentChats);
} else {
// 没有找到这条数据,直接添加到数组最前面
this.recentChats.unshift({
contactName: contactName,
content: newMessage.content,
createdAt: newMessage.createdAt,
unreadCount: 1,
});
}
},
websocketOnOpen() {},
websocketOnMessage(data) {
// 格式如下:
// {
// type: "newMessage",
// message: {
// "messageId": 146,
// "senderName": "admin",
// "receiverName": "query",
// "content": "好的额没关系",
// "createdAt": "2026-09-22T06:38:13.000Z"
// }
// }
if (data.type !== "newMessage") {
return;
}
const message = data.message;
const senderName = message.senderName;
const currentContactName =
this.currentContact && this.currentContact.contactName;
// 是当前聊天联系人
if (senderName === currentContactName) {
this.contactMessages.push({
...message,
from: "other",
time: message.createdAt,
});
} else {
// 不是当前联系人,不加入 contactMessages,只更新最近聊天列表、未读数量
this.updateRecentChat("receive", senderName, message);
}
this.$nextTick(() => {
this.scrollToBottom();
});
},
websocketOnErr() {
this.$message.error("网络连接失败,请重试");
this.logout();
},
createWebsocket() {
const token = this.$store.state.token;
const jwtToken = token.replace("Bearer ", "");
connectWebSocket(
encodeURIComponent(jwtToken),
this.websocketOnMessage,
this.websocketOnOpen,
null,
this.websocketOnErr
);
},
// 滚动到底部
scrollToBottom() {
const messageList = this.$refs.messageList;
if (messageList) {
console.log("滚动到底部", messageList.scrollHeight);
messageList.scrollTop = messageList.scrollHeight;
}
},
// 处理聊天框滚动事件
async handleMessageScroll() {
if (this.loadingMore || this.loadEnd) {
return;
}
if (!this.firstLoad) {
const el = this.$refs.messageList;
// 滚动到顶部
if (el.scrollTop === 0) {
console.log("滚动到顶部,加载更多消息");
this.loadingMore = true;
const oldScrollHeight = el.scrollHeight;
try {
await this.getContactMessageList(
this.currentContact.contactName,
10,
this.contactMessages.length
);
// 等待 Vue DOM 更新,再计算滚动高度
await this.$nextTick();
// 让滚动条调整到原来滚动高度的位置
const newScrollHeight = el.scrollHeight;
const addedHeight = newScrollHeight - oldScrollHeight;
el.scrollTop = addedHeight;
if (el.scrollTop === 0) this.loadEnd = true; //所有数据已经加载完成,不需要再继续请求了
} finally {
this.loadingMore = false;
}
}
}
},
},
};
</script>
<style scoped>
* {
box-sizing: border-box;
}
.chat-page {
display: flex;
width: 100%;
height: 100vh;
min-width: 980px;
background: #f5f5f5;
color: #333;
overflow: hidden;
}
/* =========================
左侧导航栏(微信风格)
========================= */
.app-sidebar {
width: 78px;
height: 100%;
background: #f2f3f5;
border-right: 1px solid #e5e5e5;
display: flex;
flex-direction: column;
align-items: center;
padding: 16px 0 12px;
}
.app-logo {
width: 42px;
height: 42px;
border-radius: 12px;
background: linear-gradient(135deg, #67c23a, #4caf50);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-size: 22px;
box-shadow: 0 6px 14px rgba(103, 194, 58, 0.25);
}
.sidebar-nav {
margin-top: 20px;
display: flex;
flex-direction: column;
gap: 12px;
width: 100%;
align-items: center;
}
.nav-item {
width: 42px;
height: 42px;
border: none;
border-radius: 12px;
background: transparent;
color: #666;
font-size: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
.nav-item:hover {
background: #e9edf3;
}
.nav-item.active {
background: #dfeeff;
color: #409eff;
box-shadow: inset 0 0 0 1px rgba(64, 158, 255, 0.12);
}
.sidebar-footer {
margin-top: auto;
width: 100%;
display: flex;
justify-content: center;
}
/* =========================
左侧联系人
========================= */
.contact-panel {
width: 300px;
height: 100%;
background: #ffffff;
border-right: 1px solid #e5e5e5;
display: flex;
flex-direction: column;
}
.user-header {
height: 72px;
padding: 0 20px;
display: flex;
align-items: center;
border-bottom: 1px solid #eeeeee;
}
.avatar {
width: 42px;
height: 42px;
flex-shrink: 0;
border-radius: 50%;
background: #4c8bf5;
color: #ffffff;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
font-weight: 500;
}
.my-avatar {
background: #67c23a;
}
.my-name {
font-size: 15px;
font-weight: 600;
color: #67c23a;
}
.search-box {
padding: 12px;
background: #fafafa;
}
.search-box input {
width: 100%;
height: 34px;
padding: 0 12px;
border: 1px solid #e5e5e5;
border-radius: 4px;
outline: none;
background: #ffffff;
font-size: 13px;
}
.search-box input:focus {
border-color: #409eff;
}
.contact-list {
flex: 1;
overflow-y: auto;
}
.contact-item {
height: 70px;
padding: 0 15px;
display: flex;
align-items: center;
cursor: pointer;
position: relative;
}
.contact-item:hover {
background: #f5f5f5;
}
.contact-item.active {
background: #eaf3ff;
}
.contact-info {
flex: 1;
min-width: 0;
margin-left: 12px;
}
.contact-name {
font-size: 14px;
font-weight: 500;
}
.last-message {
margin-top: 7px;
color: #999;
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.unread {
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 10px;
background: #f56c6c;
color: #fff;
font-size: 11px;
display: flex;
align-items: center;
justify-content: center;
}
/* =========================
右侧聊天
========================= */
.chat-panel {
flex: 1;
height: 100%;
display: flex;
flex-direction: column;
background: #f5f5f5;
}
.chat-header {
height: 72px;
padding: 0 24px;
display: flex;
align-items: center;
background: #ffffff;
border-bottom: 1px solid #e5e5e5;
}
.chat-user-info {
margin-left: 12px;
}
.chat-user-name {
font-size: 16px;
font-weight: 600;
}
.chat-user-status {
margin-top: 5px;
font-size: 12px;
color: #67c23a;
}
.empty-chat {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #999;
}
.empty-icon {
margin-bottom: 15px;
font-size: 50px;
}
.empty-content {
margin-top: 15px;
font-size: 50px;
color: #999;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.message-list {
flex: 1;
padding: 25px 35px;
min-height: 0;
overflow-y: auto;
display: none;
}
.message-list.active {
display: block;
}
.message-list.empty {
display: block;
height: 100%;
}
.message-row {
display: flex;
margin-bottom: 20px;
}
.message-other {
justify-content: flex-start;
}
.message-me {
justify-content: flex-end;
}
.message-avatar {
width: 38px;
height: 38px;
font-size: 14px;
}
.message-content {
max-width: 60%;
margin: 0 10px;
clear: both;
}
.message-time {
margin-bottom: 5px;
color: #aaa;
font-size: 11px;
}
.message-me .message-time {
text-align: right;
}
.message-bubble {
padding: 10px 14px;
border-radius: 6px;
background: #ffffff;
font-size: 14px;
line-height: 1.5;
word-break: break-word;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
float: right;
}
.message-me .message-bubble {
background: #95ec69;
}
/* =========================
输入区域
========================= */
.input-panel {
height: 180px;
padding: 10px 20px 15px;
background: #ffffff;
border-top: 1px solid #e5e5e5;
}
.toolbar {
height: 30px;
display: flex;
align-items: center;
gap: 12px;
}
.toolbar button {
border: none;
background: transparent;
cursor: pointer;
font-size: 18px;
}
.input-panel textarea {
width: 100%;
height: 75px;
padding: 8px 0;
resize: none;
border: none;
outline: none;
font-size: 14px;
line-height: 1.5;
}
.send-area {
display: flex;
justify-content: flex-end;
align-items: center;
}
.enter-tip {
margin-right: 15px;
color: #aaa;
font-size: 12px;
}
.send-button {
width: 70px;
height: 32px;
border: none;
border-radius: 4px;
background: #409eff;
color: #ffffff;
cursor: pointer;
}
.send-button:hover {
background: #66b1ff;
}
.send-button:disabled {
background: #c0c4cc;
cursor: not-allowed;
}
/* 滚动条 */
.contact-list::-webkit-scrollbar,
.message-list::-webkit-scrollbar {
width: 5px;
}
.contact-list::-webkit-scrollbar-thumb,
.message-list::-webkit-scrollbar-thumb {
background: #ddd;
border-radius: 3px;
}
</style>