vue2前端調用WebSocket有消息進行通知代碼示例
需求:
1.登錄成功后連接WebSocket
2.根據(jù)用戶id進行消息實時響應
3.有消息小紅點點亮,且需要進行聲音提示,反之
//icon+小紅點
<div class="relative right-menu-item hover-effect" @click="togglePopup">
<el-icon class="dot el-icon-message-solid"> </el-icon>
<!-- 如果有消息,顯示紅色圓點 -->
<span v-if="hasMessage" class="red-dot"></span>
<!-- 彈窗內容,根據(jù)需要顯示和隱藏 -->
<el-dialog title="審核通知" :visible.sync="showPopup" append-to-body>
<p>
{{ messageContent }}
</p>
</el-dialog>
</div>
//音頻
<div id="wrap">
<p>
<audio
:src="require('對應的文件路徑')"
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;
}// 登錄成功調用WebSocket
const ws = new WebSocket(`ws://后端域名/websocket/${需要響應數(shù)據(jù)的id}`);
// 將WebSocket實例保存到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;
}
},注意:
因為瀏覽器限制,可能會導致音頻無法播放
問題1:音頻可以播放,但是沒有聲音
處理:谷歌瀏覽器打開運行聲音播放
網(wǎng)站設置,將通知和聲音改成允許


問題2:報錯 audioDom.play() 自動播放音頻時報錯:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
處理:強制給音頻除添加了點擊事件
created() {
// 監(jiān)聽WebSocket消息
this.$ws.onmessage = (message) => {
let audio = document.getElementById("audio");
//強制添加點擊事件
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
})
}
}
// 關閉websiocket
function closeWebsocket () {
console.log('連接已關閉...')
ElementUI.Notification({
title: 'websocket',
message: '連接已關閉...',
type: 'danger',
position: 'bottom-right',
duration: 3000
})
}
/**
* 發(fā)送消息
* @param message
*/
function webSocketSend (message) {
this.socket.send(JSON.stringify(message))
}
export default {
initWebSocket, closeWebsocket, webSocketSend
}總結
到此這篇關于vue2前端調用WebSocket有消息進行通知的文章就介紹到這了,更多相關vue2調用WebSocket消息通知內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue使用axios導出后臺返回的文件流為excel表格詳解
這篇文章主要介紹了vue使用axios導出后臺返回的文件流為excel表格方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
vue2.6.10+vite2開啟template模板動態(tài)編譯的過程
這篇文章主要介紹了vue2.6.10+vite2開啟template模板動態(tài)編譯,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02
詳解Vue返回值動態(tài)生成表單及提交數(shù)據(jù)的辦法
這篇文章主要為大家介紹了Vue返回值動態(tài)生成表單及提交數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-12-12
windows下vue.js開發(fā)環(huán)境搭建教程
這篇文章主要為大家詳細介紹了windows下vue.js開發(fā)環(huán)境搭建教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
vue根據(jù)權限動態(tài)渲染按鈕、組件等的函數(shù)式組件實現(xiàn)
這篇文章主要介紹了vue根據(jù)權限動態(tài)渲染按鈕、組件等的函數(shù)式組件實現(xiàn)方式,具有很好的參考價值,希望杜大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

