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)文章
Cookbook組件形式:優(yōu)化 Vue 組件的運行時性能
本文仿照Vue Cookbook 組織形式,對優(yōu)化 Vue 組件的運行時性能進行闡述。通過基本的示例代碼給大家講解,需要的朋友參考下2018-11-11
Vue+webpack+Element 兼容問題總結(jié)(小結(jié))
這篇文章主要介紹了Vue+webpack+Element 兼容問題總結(jié)(小結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
Vue-cli 如何將px轉(zhuǎn)化為rem適配移動端
這篇文章主要介紹了Vue-cli 如何將px轉(zhuǎn)化為rem適配移動端,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-07-07

