vue2前端調(diào)用WebSocket有消息進(jìn)行通知代碼示例
需求:
1.登錄成功后連接WebSocket
2.根據(jù)用戶id進(jìn)行消息實(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('對應(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的全局屬性中,以便在組件中訪問
Vue.prototype.$ws = ws;
data() {
return {
hasMessage: false,
showPopup: false,
messageContent: "",
};
},
created() {
// 監(jiān)聽WebSocket消息
this.$ws.onmessage = (message) => {
let audio = document.getElementById("audio");
audio.currentTime = 0; //從頭開始播放
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覽器限制,可能會導(dǎo)致音頻無法播放
問題1:音頻可以播放,但是沒有聲音
處理:谷歌瀏覽器打開運(yùn)行聲音播放
網(wǎng)站設(shè)置,將通知和聲音改成允許


問題2:報(bào)錯 audioDom.play() 自動播放音頻時報(bào)錯:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
處理:強(qiáng)制給音頻除添加了點(diǎn)擊事件
created() {
// 監(jiān)聽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; //從頭開始播放
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ǒng)發(fā)送通知
1.初始化websocket
此處存放于layout.vue中用于連接與斷開
mounted () {
this.$websocket.initWebSocket()
},
destroyed () {
// 離開路由之后斷開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ā)生錯誤' + 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在Vue項(xiàng)目中添加接口監(jiān)聽遮罩
這篇文章主要介紹了如何在Vue項(xiàng)目中添加接口監(jiān)聽遮罩,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
vue使用axios導(dǎo)出后臺返回的文件流為excel表格詳解
這篇文章主要介紹了vue使用axios導(dǎo)出后臺返回的文件流為excel表格方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
vue2.6.10+vite2開啟template模板動態(tài)編譯的過程
這篇文章主要介紹了vue2.6.10+vite2開啟template模板動態(tài)編譯,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
詳解關(guān)于Vuex的action傳入多個參數(shù)的問題
這篇文章主要介紹了詳解關(guān)于Vuex的action傳入多個參數(shù)的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
詳解Vue返回值動態(tài)生成表單及提交數(shù)據(jù)的辦法
這篇文章主要為大家介紹了Vue返回值動態(tài)生成表單及提交數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-12-12
windows下vue.js開發(fā)環(huán)境搭建教程
這篇文章主要為大家詳細(xì)介紹了windows下vue.js開發(fā)環(huán)境搭建教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
vue根據(jù)權(quán)限動態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)
這篇文章主要介紹了vue根據(jù)權(quán)限動態(tài)渲染按鈕、組件等的函數(shù)式組件實(shí)現(xiàn)方式,具有很好的參考價值,希望杜大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

