更新时间:2024年07月26日 16:47:15 作者:lili@
在Vue项目中实现全局的消息链接监听主要涉及到了WebSocket技术,这是一种双向通信协议,允许客户端与服务器之间实时、高效地交换数据,这篇文章主要给大家介绍了关于vue2前端调用WebSocket有消息进行通知的相关资料,需要的朋友可以参考下
需求:
1.登录成功后连接WebSocket
2.根据用户id进行消息实时响应
3.有消息小红点点亮,且需要进行声音提示,反之
//icon+小红点 //音频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/${需要响应数据的id}`);
// 将WebSocket实例保存到Vue的全局属性中,以便在组件中访问
Vue.prototype.$ws = ws;
data() {
return {
hasMessage: false,
showPopup: false,
messageContent: "",
};
},
created() {
// 监听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);
});
// 改变铃铛状态
this.hasMessage = true;
this.messageContent = message.data;
};
},
togglePopup() {
if (this.messageContent != "") {
this.showPopup = true;
}
},
注意:
因为浏览器限制,可能会导致音频无法播放
问题1:音频可以播放,但是没有声音
处理:谷歌浏览器打开运行声音播放
网站设置,将通知和声音改成允许
问题2:报错 audioDom.play() 自动播放音频时报错:Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
处理:强制给音频除添加了点击事件
created() {
// 监听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);
});
// 改变铃铛状态
this.hasMessage = true;
this.messageContent = message.data;
};
},
附:vue2中使用websocket用于后台管理系统发送通知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连接发生错误' + 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) {
// 更新消息通知条数
store.dispatch('admin/messagecenter/setUnread')
}
if (systemConfig) {
// 更新系统配置
this.$store.dispatch('admin/settings/load')
}
if (data.contentType === 'SYSTEM') {
ElementUI.Notification({
title: '系统消息',
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
})
}
/**
* 发送消息
* @param message
*/
function webSocketSend (message) {
this.socket.send(JSON.stringify(message))
}
export default {
initWebSocket, closeWebsocket, webSocketSend
}
总结
到此这篇关于vue2前端调用WebSocket有消息进行通知的文章就介绍到这了,更多相关vue2调用WebSocket消息通知内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
