vue3使用全局websocket的示例详解

 更新时间:2023年10月19日 09:41:50   作者:CUI_PING  
这篇文章主要为大家详细介绍了vue3使用全局websocket的相关知识,文中的示例代码讲解详细,对我们深入学习vue3有一定的帮助,感兴趣的小伙伴可以参考一下

思路:

一: 使用store 定义websocket 全局封装类 websocket.js

const useSocketStore = defineStore(
  'socket',
  {
    state: () => ({
      ws: undefined,
      heartTimeOut: 40000, //监测心跳时间 40秒
      //this.isReConnection = false
      lockReconnect: false, //避免重连
      timerReconnect: undefined,
      timerHeart: undefined,
      timerServerHeart: undefined,
      handClose: false,
      msg: ""
    }),
    actions: {
      connection(url, token){
        if("WebSocket" in window){
          this.createWebSocket(url, token)
          
        }
        else{
          console.log("您的浏览器不支持websocket通信")
        }    
      },
    
      //初始化
      createWebSocket(url, token){
        try{
          this.ws = new WebSocket(url, token)  // 
          
          this.initWebsocket()
          
        }
        catch(e){
          console.log("catch eeeee=", e)
          this.reConnection()
        }
      },
    
      initWebsocket(){
    
        //建立连接
        this.ws.onopen = (e)=>{
         
          //webSocket业务订阅——可以有多个业务
          this.ws.send("hello server");
          console.log("连接成功")
          //连接成功后,需要开启监测心跳
          this.heartCheck()
        }
    
        this.ws.onmessage = (messages)=>{
         
          console.log(messages.data)
          let msg = messages.data
          if(msg.includes("{")){
            msg = JSON.parse(msg)
          }
          this.msg = msg

          //接收到消息后,需要开启监测心跳
          this.heartCheck()
        }
    
      
        this.ws.onerror = (e)=>{       //连不上时onerror 和 onclose 监听同时会捕捉到
          console.log("连接失败")
          // 连失败需要重连
          this.reConnection()
        }
    
        this.ws.onclose = (e)=>{
          console.log("关闭连接")
         
          //是否正常关闭  正常关闭不需要重连, 否则需要重连
          if(!this.handClose){
            this.reConnection()
          }
        }
      },
    
      clearTimer(){
        this.timerReconnect && clearTimeout(this.timerReconnect)
        this.timerHeart && clearTimeout(this.timerHeart)
        this.timerServerHeart && clearTimeout(this.timerServerHeart)
      },
    
      //重连
      reConnection(){
        console.log("重新连接")
        if(this.lockReconnect){
          return
        }
        this.lockReconnect = true
        if(this.timerReconnect) {
          clearTimeout(this.timerReconnect)
        } 
    
        //没连上会一直重连, 设置迟延,避免请求过多
        this.timerReconnect = setTimeout(() => { //setTimeout 到点了执行
          this.connection()
          this.lockReconnect = false
        }, 5000);
        
      },
      
    
      //心跳
      heartCheck(){
        console.log("监测心跳")
        if(this.timerHeart){
          clearTimeout(this.timerHeart)
        }
    
        // if(this.timerServerHeart){
        //   clearTimeout(this.timerServerHeart)
        // }
    
        this.timerHeart = setTimeout(() => {
          console.log("PING");
          this.ws.send("PING");
    
          // this.timerServerHeart = setTimeout(() => {
          //   // 断了
          //   this.ws.close()
          // }, 5000);
    
          this.lockReconnect = false
        }, this.heartTimeOut); //40秒
    
      },
    
      //发送消息
      sendMsg(data){
        console.log("发送消息")
        if(this.ws.readyState === WebSocket.OPEN){
          this.ws.send(JSON.stringify(data))
        }
      },
    
      //关闭连接 手动关闭
      closeWs(){
        console.log("手动关闭ws")
        this.handClose = true
        this.clearTimer()
        this.ws.close()
      }
    }
  })

export default useSocketStore

二: 在全局组件中引入,并初始化websocket 连接

import useSocketStore from '@/store/modules/websocket'
import { getToken } from '@/utils/auth'
import  useUserStore from "@/store/modules/user.js"
const userStore = useUserStore();

const socketStore = useSocketStore();

onMounted(()=>{
  let url = `${import.meta.env.VITE_APP_SOCKET_URL}/1/${userStore.userId}/`;
  let token= getToken();

  socketStore.connection(url, token);
})
onUnmounted(()=>{
  socketStore.closeWs();
})

三: 在各个组件中使用watch 监听接收消息内容的变更

watch(() => socketStore.msg, messages => {
  if(messages.mesType === "order"){
    newMessage.value = true;
  }  
})

到此这篇关于vue3使用全局websocket的示例详解的文章就介绍到这了,更多相关vue3全局websocket内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue3中7种路由守卫的使用大全举例

    vue3中7种路由守卫的使用大全举例

    最近在学习vue,感觉路由守卫这个地方知识点挺多的,而且很重要,下面这篇文章主要给大家介绍了关于vue3中7种路由守卫的使用大全,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-03-03
  • React DOM diff 对比Vue DOM diff 区别详解

    React DOM diff 对比Vue DOM diff 

    这篇文章主要为大家介绍了React DOM diff 对比Vue DOM diff 区别详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 前端vue3项目中百度地图的使用api以及操作实例

    前端vue3项目中百度地图的使用api以及操作实例

    最近项目要用到百度地图api,好久没用到地图,就百度了一番,但是找了好几篇文章,发现都没办法成功实现,现将方法记录如下,下面这篇文章主要给大家介绍了关于前端vue3项目中百度地图的使用api以及操作实例,需要的朋友可以参考下
    2023-05-05
  • vue内置动态组件component使用示例小结

    vue内置动态组件component使用示例小结

    component是vue内置组件,主要作用为动态渲染组件,这篇文章主要介绍了vue内置动态组件component使用示例小结,需要的朋友可以参考下
    2024-03-03
  • VUE DEMO之模拟登录个人中心页面之间数据传值实例

    VUE DEMO之模拟登录个人中心页面之间数据传值实例

    今天小编就为大家分享一篇VUE DEMO之模拟登录个人中心页面之间数据传值实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-10-10
  • 最全vue的vue-amap使用高德地图插件画多边形范围的示例代码

    最全vue的vue-amap使用高德地图插件画多边形范围的示例代码

    这篇文章主要介绍了最全vue的vue-amap使用高德地图插件画多边形范围,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • vue3 文档梳理快速入门

    vue3 文档梳理快速入门

    vue3之所以受广大袁友的喜欢,优点必不可少呀,比如:可以监听动态新增的属性;可以监听删除的属性 ;可以监听数组的索引和 length 属性;下面文章小编就来向大家介绍vue3,感兴趣的小伙伴不要错过奥
    2021-09-09
  • 基于Vue uniapp实现贪吃蛇游戏

    基于Vue uniapp实现贪吃蛇游戏

    贪吃蛇游戏想必是很多70、80后的回忆,一直到现在也深受大家的喜欢。本文将利用Vue+uniapp实现这一经典的游戏,感兴趣的可以了解一下
    2022-04-04
  • axios库的核心代码解析及总结

    axios库的核心代码解析及总结

    这篇博客针对axios库的核心代码做一个简要总结,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • Vue.js中v-bind指令的用法介绍

    Vue.js中v-bind指令的用法介绍

    这篇文章介绍了Vue.js中v-bind指令的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03

最新评论