|
@@ -1,7 +1,12 @@
|
|
|
<script setup lang="ts">
|
|
|
import { Dialog } from '@/components/Dialog'
|
|
|
import { shallowRef, defineAsyncComponent, DefineComponent } from 'vue'
|
|
|
-import { webSocketStore } from '@/store/modules/webSocketStore'
|
|
|
+import { getAccessToken } from '@/utils/auth'
|
|
|
+import { useWebSocket } from '@vueuse/core'
|
|
|
+import { imMessageStore, ImMessageWebSocket } from '@/store/modules/imMessageStore'
|
|
|
+
|
|
|
+// 从 imMessageStore 中导入 addMessage 方法
|
|
|
+const { addMessage } = imMessageStore()
|
|
|
|
|
|
// 异步加载可能的对话框内容组件
|
|
|
const IMComponent = defineAsyncComponent(() => import('@/views/im/index.vue'))
|
|
@@ -14,11 +19,61 @@ function openDialog() {
|
|
|
dialogVisible.value = true
|
|
|
currentComponent.value = IMComponent // 加载 IM 组件
|
|
|
}
|
|
|
-// 登录成功后初始化 WebSocket 连接
|
|
|
-const { status, data, initWebSocket } = webSocketStore()
|
|
|
|
|
|
-/** 监听接收到的数据 */
|
|
|
-const messageList = ref([] as { time: number; text: string }[]) // 消息列表
|
|
|
+// 初始化 WebSocket 连接
|
|
|
+function initWebSocket() {
|
|
|
+ const server =
|
|
|
+ (import.meta.env.VITE_BASE_URL + '/infra/ws').replace('http', 'ws') +
|
|
|
+ '?token=' +
|
|
|
+ getAccessToken()
|
|
|
+ const { data } = useWebSocket(server, {
|
|
|
+ autoReconnect: true,
|
|
|
+ heartbeat: true,
|
|
|
+ onMessage(ws, event) {
|
|
|
+ // ws 状态不是 open 时不处理
|
|
|
+ if (ws.readyState !== WebSocket.OPEN) return
|
|
|
+ try {
|
|
|
+ // 1. 收到心跳
|
|
|
+ if (data.value === 'pong') {
|
|
|
+ console.log('websocket 收到心跳包')
|
|
|
+ return
|
|
|
+ }
|
|
|
+ console.log('websocket 收到消息', event.data)
|
|
|
+ // 2.1 解析 type 消息类型
|
|
|
+ const jsonMessage = JSON.parse(data.value)
|
|
|
+ const type = jsonMessage.type
|
|
|
+ const content = JSON.parse(jsonMessage.content)
|
|
|
+ if (!type) {
|
|
|
+ // message.error('未知的消息类型:' + data.value)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ // 2.2 消息类型:demo-message-receive
|
|
|
+ if (type === 'im-message-receive') {
|
|
|
+ const message: ImMessageWebSocket = {
|
|
|
+ id: content.id,
|
|
|
+ conversationType: content.conversationType,
|
|
|
+ senderId: content.senderId,
|
|
|
+ senderNickname: content.senderNickname,
|
|
|
+ senderAvatar: content.senderAvatar,
|
|
|
+ receiverId: content.receiverId,
|
|
|
+ contentType: content.contentType,
|
|
|
+ content: content.content,
|
|
|
+ sendTime: content.sendTime,
|
|
|
+ sequence: content.sequence
|
|
|
+ }
|
|
|
+
|
|
|
+ // 保存到 pina imMessageStore
|
|
|
+ addMessage(message)
|
|
|
+
|
|
|
+ return
|
|
|
+ }
|
|
|
+ } catch (error) {
|
|
|
+ console.error(error)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ })
|
|
|
+ console.log('websocket 初始化成功')
|
|
|
+}
|
|
|
|
|
|
// ========== 初始化 =========
|
|
|
onMounted(() => {
|