欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3使用全局websocket的示例詳解

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

思路:

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

const useSocketStore = defineStore(
  'socket',
  {
    state: () => ({
      ws: undefined,
      heartTimeOut: 40000, //監(jiān)測心跳時間 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ù)訂閱——可以有多個業(yè)務(wù)
          this.ws.send("hello server");
          console.log("連接成功")
          //連接成功后,需要開啟監(jiān)測心跳
          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)測心跳
          this.heartCheck()
        }
    
      
        this.ws.onerror = (e)=>{       //連不上時onerror 和 onclose 監(jiān)聽同時會捕捉到
          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)
        } 
    
        //沒連上會一直重連, 設(shè)置遲延,避免請求過多
        this.timerReconnect = setTimeout(() => { //setTimeout 到點了執(zhí)行
          this.connection()
          this.lockReconnect = false
        }, 5000);
        
      },
      
    
      //心跳
      heartCheck(){
        console.log("監(jiān)測心跳")
        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)閉連接 手動關(guān)閉
      closeWs(){
        console.log("手動關(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();
})

三: 在各個組件中使用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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 關(guān)于vue中api統(tǒng)一管理的那些事

    關(guān)于vue中api統(tǒng)一管理的那些事

    最近在學(xué)習(xí)Vue教程,下面這篇文章主要給大家介紹了關(guān)于vue中api統(tǒng)一管理的那些事,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-04-04
  • Vue模擬el-table演示插槽用法的示例詳解

    Vue模擬el-table演示插槽用法的示例詳解

    很多人知道插槽分為三種,但是實際到elementui當(dāng)中為什么這么用,就一臉懵逼,接下來就跟大家聊一聊插槽在elementui中的應(yīng)用,并且自己寫一個類似el-table的組件,感興趣的可以了解一下
    2023-05-05
  • Cookbook組件形式:優(yōu)化 Vue 組件的運行時性能

    Cookbook組件形式:優(yōu)化 Vue 組件的運行時性能

    本文仿照Vue Cookbook 組織形式,對優(yōu)化 Vue 組件的運行時性能進(jìn)行闡述。通過基本的示例代碼給大家講解,需要的朋友參考下
    2018-11-11
  • Vue框架中正確引入JS庫的方法介紹

    Vue框架中正確引入JS庫的方法介紹

    最近在學(xué)習(xí)使用vue框架,在使用中遇到了一個問題,查找相關(guān)資料終于找了正確的姿勢,所以這篇文章主要給大家介紹了關(guān)于在Vue框架中正確引入JS庫的方法,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • Vue+webpack+Element 兼容問題總結(jié)(小結(jié))

    Vue+webpack+Element 兼容問題總結(jié)(小結(jié))

    這篇文章主要介紹了Vue+webpack+Element 兼容問題總結(jié)(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-08-08
  • axios+Vue實現(xiàn)上傳文件顯示進(jìn)度功能

    axios+Vue實現(xiàn)上傳文件顯示進(jìn)度功能

    這篇文章主要介紹了axios+Vue上傳文件顯示進(jìn)度效果,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-04-04
  • Vue路由守衛(wèi)之路由獨享守衛(wèi)

    Vue路由守衛(wèi)之路由獨享守衛(wèi)

    這篇文章主要介紹了Vue路由守衛(wèi)之路由獨享守衛(wèi)的代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-09-09
  • Vue插件之滑動驗證碼用法詳解

    Vue插件之滑動驗證碼用法詳解

    這篇文章主要介紹了Vue插件之滑動驗證碼用法,結(jié)合實例形式詳細(xì)分析了Vue滑動驗證碼插件相關(guān)使用方法與操作注意事項,需要的朋友可以參考下
    2020-04-04
  • Vue-cli 如何將px轉(zhuǎn)化為rem適配移動端

    Vue-cli 如何將px轉(zhuǎn)化為rem適配移動端

    這篇文章主要介紹了Vue-cli 如何將px轉(zhuǎn)化為rem適配移動端,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-07-07
  • 學(xué)習(xí)vue.js計算屬性

    學(xué)習(xí)vue.js計算屬性

    這篇文章主要和大家一起學(xué)習(xí)vue.js的計算屬性,分享一些計算屬性練習(xí)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-12-12

最新評論