vue3+element+ts使用signalR

10 篇文章 0 订阅
8 篇文章 0 订阅

1、创建实例

const http = new Tool().http
const token=localStorage.getItem('token')?localStorage.getItem('token'):''  
const connection = new signalR.HubConnectionBuilder()
  .withUrl(http+"/event", {
    accessTokenFactory:()=>{               
           let t ="Bearer "+token
           return t ;    
       },
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets,
        
   })
  .build();

2、创建服务端长连接推送消息

//监听服务端长连接的推送消息
const emits = defineEmits(["tongXin"])

3、监听事件消息

//监听有新的待办事项
connection.on("OrderFlowChanged",(message) =>{
  console.log('有新的待办事项推送的消息',message)

    ElNotification({
            title: '提示消息',
            message: '您有新的待办事项,请前往订单中心-订单列表中处理!',
            duration: 10000,
    })
    emits('tongXin', message)
})

4、通信开始

async function start() {
    try {
        await connection.start();
        console.log("SignalR Connected.通信开始");
    } catch (err) {
        console.log(err,'通信报错');
        if(isLogin.value){
            console.log('重新链接')
            setTimeout(start, 5000);
        }else{
            connection.stop();//窗口关闭断开通信
        }
    }
};
// 断线重连
connection.onclose(async () => {
      console.log('断开连接了????????????')
      if(isLogin.value){
        console.log('重新链接')
        await start();
      }else{
        connection.stop();//窗口关闭断开通信
      }
});
onMounted(() => {
    start();
})
//窗口销毁后
onUnmounted(() => {
    isLogin.value=false
    connection.stop();//窗口关闭断开通信
})

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值