最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3使用全局websocket的示例詳解

 更新時(shí)間:2023年10月19日 09:41:50   作者:CUI_PING  
這篇文章主要為大家詳細(xì)介紹了vue3使用全局websocket的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),對(duì)我們深入學(xué)習(xí)vue3有一定的幫助,感興趣的小伙伴可以參考一下

思路:

一: 使用store 定義websocket 全局封裝類 websocket.js

const useSocketStore = defineStore(
  'socket',
  {
    state: () => ({
      ws: undefined,
      heartTimeOut: 40000, //監(jiān)測(cè)心跳時(shí)間 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業(yè)務(wù)訂閱——可以有多個(gè)業(yè)務(wù)
          this.ws.send("hello server");
          console.log("連接成功")
          //連接成功后,需要開啟監(jiān)測(cè)心跳
          this.heartCheck()
        }
    
        this.ws.onmessage = (messages)=>{
         
          console.log(messages.data)
          let msg = messages.data
          if(msg.includes("{")){
            msg = JSON.parse(msg)
          }
          this.msg = msg

          //接收到消息后,需要開啟監(jiān)測(cè)心跳
          this.heartCheck()
        }
    
      
        this.ws.onerror = (e)=>{       //連不上時(shí)onerror 和 onclose 監(jiān)聽同時(shí)會(huì)捕捉到
          console.log("連接失敗")
          // 連失敗需要重連
          this.reConnection()
        }
    
        this.ws.onclose = (e)=>{
          console.log("關(guān)閉連接")
         
          //是否正常關(guān)閉  正常關(guān)閉不需要重連, 否則需要重連
          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)
        } 
    
        //沒連上會(huì)一直重連, 設(shè)置遲延,避免請(qǐng)求過多
        this.timerReconnect = setTimeout(() => { //setTimeout 到點(diǎn)了執(zhí)行
          this.connection()
          this.lockReconnect = false
        }, 5000);
        
      },
      
    
      //心跳
      heartCheck(){
        console.log("監(jiān)測(cè)心跳")
        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秒
    
      },
    
      //發(fā)送消息
      sendMsg(data){
        console.log("發(fā)送消息")
        if(this.ws.readyState === WebSocket.OPEN){
          this.ws.send(JSON.stringify(data))
        }
      },
    
      //關(guān)閉連接 手動(dòng)關(guān)閉
      closeWs(){
        console.log("手動(dòng)關(guān)閉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();
})

三: 在各個(gè)組件中使用watch 監(jiān)聽接收消息內(nèi)容的變更

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

到此這篇關(guān)于vue3使用全局websocket的示例詳解的文章就介紹到這了,更多相關(guān)vue3全局websocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

张家界市| 鄂伦春自治旗| 罗田县| 石林| 禹城市| 特克斯县| 泰州市| 云龙县| 绥化市| 东兰县| 布尔津县| 锡林浩特市| 三河市| 巴南区| 平泉县| 台州市| 新乡市| 竹溪县| 黄冈市| 隆尧县| 宁河县| 灌云县| 延寿县| 闵行区| 新民市| 工布江达县| 安国市| 云梦县| 新竹县| 玉树县| 都江堰市| 玉林市| 息烽县| 四子王旗| 长阳| 天柱县| 威海市| 鹤岗市| 鹤壁市| 霍州市| 三明市|