vue2前端調(diào)用WebSocket有消息進(jìn)行通知代碼示例
需求:
1.登錄成功后連接WebSocket
2.根據(jù)用戶(hù)id進(jìn)行消息實(shí)時(shí)響應(yīng)
3.有消息小紅點(diǎn)點(diǎn)亮,且需要進(jìn)行聲音提示,反之
//icon+小紅點(diǎn) <div class="relative right-menu-item hover-effect" @click="togglePopup"> <el-icon class="dot el-icon-message-solid"> </el-icon> <!-- 如果有消息,顯示紅色圓點(diǎn) --> <span v-if="hasMessage" class="red-dot"></span> <!-- 彈窗內(nèi)容,根據(jù)需要顯示和隱藏 --> <el-dialog title="審核通知" :visible.sync="showPopup" append-to-body> <p> {{ messageContent }} </p> </el-dialog> </div> //音頻 <div id="wrap"> <p> <audio :src="require('對(duì)應(yīng)的文件路徑')" id="audio" preload="auto" muted type="audio/mp3" controls="controls" ></audio> </p> </div> css樣式 .dot { position: absolute; top: 14px; right: 190px; font-size: 20px; } .red-dot { position: absolute; top: 14px; right: 190px; height: 10px; width: 10px; background-color: red; border-radius: 50%; z-index: 999; } #wrap { display: none; }
// 登錄成功調(diào)用WebSocket const ws = new WebSocket(`ws://后端域名/websocket/${需要響應(yīng)數(shù)據(jù)的id}`); // 將WebSocket實(shí)例保存到Vue的全局屬性中,以便在組件中訪問(wèn) Vue.prototype.$ws = ws; data() { return { hasMessage: false, showPopup: false, messageContent: "", }; }, created() { // 監(jiān)聽(tīng)WebSocket消息 this.$ws.onmessage = (message) => { let audio = document.getElementById("audio"); audio.currentTime = 0; //從頭開(kāi)始播放 audio.muted = false; //取消靜音 audio.play().then(() => { // 播放成功 console.log('音頻播放成功'); }).catch((error) => { // 播放失敗 console.error('音頻播放失敗', error); }); // 改變鈴鐺狀態(tài) this.hasMessage = true; this.messageContent = message.data; }; }, togglePopup() { if (this.messageContent != "") { this.showPopup = true; } },
注意:
因?yàn)闉g覽器限制,可能會(huì)導(dǎo)致音頻無(wú)法播放
問(wèn)題1:音頻可以播放,但是沒(méi)有聲音
處理:谷歌瀏覽器打開(kāi)運(yùn)行聲音播放
網(wǎng)站設(shè)置,將通知和聲音改成允許
問(wèn)題2:報(bào)錯(cuò) audioDom.play() 自動(dòng)播放音頻時(shí)報(bào)錯(cuò):Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
處理:強(qiáng)制給音頻除添加了點(diǎn)擊事件
created() { // 監(jiān)聽(tīng)WebSocket消息 this.$ws.onmessage = (message) => { let audio = document.getElementById("audio"); //強(qiáng)制添加點(diǎn)擊事件 let playButton = document.getElementById("wrap"); var event = new MouseEvent("click", { bubbles: true, cancelable: true, view: window, }); playButton.dispatchEvent(event); audio.currentTime = 0; //從頭開(kāi)始播放 audio.muted = false; //取消靜音 audio.play().then(() => { // 播放成功 console.log('音頻播放成功'); }).catch((error) => { // 播放失敗 console.error('音頻播放失敗', error); }); // 改變鈴鐺狀態(tài) this.hasMessage = true; this.messageContent = message.data; }; },
附:vue2中使用websocket用于后臺(tái)管理系統(tǒng)發(fā)送通知
1.初始化websocket
此處存放于layout.vue中用于連接與斷開(kāi)
mounted () { this.$websocket.initWebSocket() }, destroyed () { // 離開(kāi)路由之后斷開(kāi)websocket連接 this.$websocket.closeWebsocket() }
2.websocket.js
import ElementUI from 'element-ui' import util from '@/libs/util' import store from '@/store' function initWebSocket (e) { const token = util.cookies.get('token') if (token) { const wsUri = util.wsBaseURL() + 'ws/' + token + '/' this.socket = new WebSocket(wsUri)// 這里面的this都指向vue this.socket.onerror = webSocketOnError this.socket.onmessage = webSocketOnMessage this.socket.onclose = closeWebsocket } } function webSocketOnError (e) { ElementUI.Notification({ title: '', message: 'WebSocket連接發(fā)生錯(cuò)誤' + JSON.stringify(e), type: 'error', position: 'bottom-right', duration: 3000 }) } /** * 接收消息 * @param e * @returns {any} */ function webSocketOnMessage (e) { const data = JSON.parse(e.data) const { refreshUnread, systemConfig } = data if (refreshUnread) { // 更新消息通知條數(shù) store.dispatch('admin/messagecenter/setUnread') } if (systemConfig) { // 更新系統(tǒng)配置 this.$store.dispatch('admin/settings/load') } if (data.contentType === 'SYSTEM') { ElementUI.Notification({ title: '系統(tǒng)消息', message: data.content, type: 'success', position: 'bottom-right', duration: 3000 }) } else if (data.contentType === 'ERROR') { ElementUI.Notification({ title: '', message: data.content, type: 'error', position: 'bottom-right', duration: 0 }) } else if (data.contentType === 'INFO') { ElementUI.Notification({ title: '溫馨提示', message: data.content, type: 'success', position: 'bottom-right', duration: 0 }) } else { ElementUI.Notification({ title: '溫馨提示', message: data.content, type: 'info', position: 'bottom-right', duration: 3000 }) } } // 關(guān)閉websiocket function closeWebsocket () { console.log('連接已關(guān)閉...') ElementUI.Notification({ title: 'websocket', message: '連接已關(guān)閉...', type: 'danger', position: 'bottom-right', duration: 3000 }) } /** * 發(fā)送消息 * @param message */ function webSocketSend (message) { this.socket.send(JSON.stringify(message)) } export default { initWebSocket, closeWebsocket, webSocketSend }
總結(jié)
到此這篇關(guān)于vue2前端調(diào)用WebSocket有消息進(jìn)行通知的文章就介紹到這了,更多相關(guān)vue2調(diào)用WebSocket消息通知內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue狀態(tài)管理庫(kù)Pinia詳細(xì)介紹
這篇文章主要介紹了Vue3-pinia狀態(tài)管理,pinia是 vue3 新的狀態(tài)管理工具,簡(jiǎn)單來(lái)說(shuō)相當(dāng)于之前 vuex,它去掉了 Mutations 但是也是支持 vue2 的,需要的朋友可以參考下2022-08-08如何在Vue項(xiàng)目中添加接口監(jiān)聽(tīng)遮罩
這篇文章主要介紹了如何在Vue項(xiàng)目中添加接口監(jiān)聽(tīng)遮罩,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01vue.js云存儲(chǔ)實(shí)現(xiàn)圖片上傳功能
示對(duì)象存儲(chǔ)是騰訊云提供的一種存儲(chǔ)海量文件的分布式存儲(chǔ)服務(wù),本文主要介紹了用vue.js實(shí)現(xiàn)圖片上傳功能,感興趣的小伙伴們可以參考一下2021-05-05vue使用axios導(dǎo)出后臺(tái)返回的文件流為excel表格詳解
這篇文章主要介紹了vue使用axios導(dǎo)出后臺(tái)返回的文件流為excel表格方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08vue2.6.10+vite2開(kāi)啟template模板動(dòng)態(tài)編譯的過(guò)程
這篇文章主要介紹了vue2.6.10+vite2開(kāi)啟template模板動(dòng)態(tài)編譯,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-02-02詳解關(guān)于Vuex的action傳入多個(gè)參數(shù)的問(wèn)題
這篇文章主要介紹了詳解關(guān)于Vuex的action傳入多個(gè)參數(shù)的問(wèn)題,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02詳解Vue返回值動(dòng)態(tài)生成表單及提交數(shù)據(jù)的辦法
這篇文章主要為大家介紹了Vue返回值動(dòng)態(tài)生成表單及提交數(shù)據(jù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2021-12-12windows下vue.js開(kāi)發(fā)環(huán)境搭建教程
這篇文章主要為大家詳細(xì)介紹了windows下vue.js開(kāi)發(fā)環(huán)境搭建教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03vue根據(jù)權(quán)限動(dòng)態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)
這篇文章主要介紹了vue根據(jù)權(quán)限動(dòng)態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望杜大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11vue cli使用絕對(duì)路徑引用圖片問(wèn)題的解決
這篇文章主要給大家介紹了關(guān)于vue cli使用絕對(duì)路徑引用圖片問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起看看吧。2017-12-12