前端:

引用signalr三方包
This commit is contained in:
2026-01-19 19:37:47 +08:00
parent e7dbb651a2
commit 507788f6a3
9 changed files with 274 additions and 9 deletions
View File
+44
View File
@@ -0,0 +1,44 @@
import { defineStore } from "pinia";
import * as signalR from '@microsoft/signalr';
import { useMessage } from "@/components/messages/useAlert";
import { useAuthStore } from "./auth";
const message = useMessage()
const authStore = useAuthStore()
export const useSignalRStore = defineStore('signalr', {
state: () => ({
connection: null,
isConnected: false
}),
actions: {
async initSignalR() {
const url = import.meta.env.VITE_SIGNALR_BASE_URL || 'http://localhost:5202/chat';
this.connection = new signalR.HubConnectionBuilder()
.withUrl(url, {
accessTokenFactory: () => {
return authStore.token;
}
})
.withAutomaticReconnect()
.build();
this.registerHandlers();
try {
await this.connection.start();
this.isConnected = true;
console.log('SignalR建立通信成功!')
} catch (e) {
message.error('与服务器建立通信失败,请检查网络连接...');
}
},
registerHandlers() {
this.connection.on('ReceiveMessage', (msg) => {
console.log(msg)
});
this.connection.onclose(() => { this.isConnected = false });
this.connection.onreconnected(() => { this.isConnected = true });
}
}
})