这段代码是一个 Vue.js 组件,通过调用 SignalR 的 API 实现实时通信功能。具体分析如下:
- 导入模块:
import {getCurrentInstance} from 'vue';
import * as signalR from '@microsoft/signalr';
import { ElNotification } from 'element-plus';
导入了 vue
库中的 getCurrentInstance
方法、SignalR 库中的所有方法(使用别名 signalR
)以及 Element-Plus 库中的 ElNotification
组件。
- 定义组件:
export default function (http, receive) {
// ...
}
定义了一个默认导出的函数,接受两个参数:http
和 receive
。
- 发送请求获取当前用户信息:
http.post('api/user/GetCurrentUserInfo').then((result) => {
connection = new signalR.HubConnectionBuilder()
.withAutomaticReconnect()
.withUrl(`${http.ipAddress}message?userName=${result.data.userName}`)
//.withUrl(`${http.ipAddress}message`)
.build();
// ...
});
通过发送 HTTP POST 请求获取当前用户信息,并在 Promise 回调中创建 SignalR 连接对象。其中,.withAutomaticReconnect()
方法表示自动重连,.withUrl()
方法指定连接 URL,${http.ipAddress}
表示服务端地址,result.data.userName
表示当前用户名。
- 启动连接并监听事件:
connection.start().catch((err) => console.log(ex.message));
// 自动重连成功后的处理
connection.onreconnected((connectionId) => {
//console.log(connectionId);
});
connection.on('ReceiveHomePageMessage', function (data) {
// ...
});
通过 connection.start()
启动连接,并监听两个事件:自动重连成功后的处理和 "ReceiveHomePageMessage"
事件。在 "ReceiveHomePageMessage"
事件中,调用 ElNotification.success
方法显示消息通知,并执行 receive
回调函数。
- 调用
$tabs.open
方法:
const { proxy } = getCurrentInstance();
proxy.$tabs.open({
text: "查看详情",
path: data.routeUrl,
query: {},
});
使用 getCurrentInstance
方法获取当前实例对象,然后通过 proxy.$tabs.open
方法打开一个新标签页,在其中展示指定的页面。其中,data.routeUrl
表示需要展示的页面地址。