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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 关于vue中api统一管理的那些事

    关于vue中api统一管理的那些事

    最近在学习Vue教程,下面这篇文章主要给大家介绍了关于vue中api统一管理的那些事,文中通过示例代码介绍的非常详细,对大家学习或者使用vue具有一定的参考学习价值,需要的朋友可以参考下
    2022-04-04
  • Vue模拟el-table演示插槽用法的示例详解

    Vue模拟el-table演示插槽用法的示例详解

    很多人知道插槽分为三种,但是实际到elementui当中为什么这么用,就一脸懵逼,接下来就跟大家聊一聊插槽在elementui中的应用,并且自己写一个类似el-table的组件,感兴趣的可以了解一下
    2023-05-05
  • Cookbook组件形式:优化 Vue 组件的运行时性能

    Cookbook组件形式:优化 Vue 组件的运行时性能

    本文仿照Vue Cookbook 组织形式,对优化 Vue 组件的运行时性能进行阐述。通过基本的示例代码给大家讲解,需要的朋友参考下
    2018-11-11
  • Vue框架中正确引入JS库的方法介绍

    Vue框架中正确引入JS库的方法介绍

    最近在学习使用vue框架,在使用中遇到了一个问题,查找相关资料终于找了正确的姿势,所以这篇文章主要给大家介绍了关于在Vue框架中正确引入JS库的方法,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-07-07
  • Vue+webpack+Element 兼容问题总结(小结)

    Vue+webpack+Element 兼容问题总结(小结)

    这篇文章主要介绍了Vue+webpack+Element 兼容问题总结(小结),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • axios+Vue实现上传文件显示进度功能

    axios+Vue实现上传文件显示进度功能

    这篇文章主要介绍了axios+Vue上传文件显示进度效果,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-04-04
  • Vue路由守卫之路由独享守卫

    Vue路由守卫之路由独享守卫

    这篇文章主要介绍了Vue路由守卫之路由独享守卫的代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • Vue插件之滑动验证码用法详解

    Vue插件之滑动验证码用法详解

    这篇文章主要介绍了Vue插件之滑动验证码用法,结合实例形式详细分析了Vue滑动验证码插件相关使用方法与操作注意事项,需要的朋友可以参考下
    2020-04-04
  • Vue-cli 如何将px转化为rem适配移动端

    Vue-cli 如何将px转化为rem适配移动端

    这篇文章主要介绍了Vue-cli 如何将px转化为rem适配移动端,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-07-07
  • 学习vue.js计算属性

    学习vue.js计算属性

    这篇文章主要和大家一起学习vue.js的计算属性,分享一些计算属性练习代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-12-12

最新评论