用戶登陸后即時(shí)推送業(yè)務(wù)信息,使用element-UI的Notification 通知進(jìn)行提示,并通過(guò)Notification 通知的onClick方法進(jìn)行頁(yè)面跳轉(zhuǎn)。
1、創(chuàng)建頁(yè)面時(shí)即生效
我寫在了首頁(yè),保證一進(jìn)入系統(tǒng)即開始接收
created() {
// 連接webSocket,用于接收后臺(tái)實(shí)時(shí)報(bào)警信息推送
this.webSocket();
},
2、websocket具體操作
methods: {
webSocket() {
const that = this;
if (typeof (WebSocket) == 'undefined') {
this.$notify({
title: '提示',
message: '當(dāng)前瀏覽器無(wú)法接收實(shí)時(shí)報(bào)警信息,請(qǐng)使用谷歌瀏覽器!',
type: 'warning',
duration: 0
});
} else {
// 獲取token保存到vuex中的用戶信息,此處僅適用于本項(xiàng)目,注意刪除或修改
store.dispatch('GetInfo').then(info => {
// 實(shí)例化socket,這里我把用戶名傳給了后臺(tái),使后臺(tái)能判斷要把消息發(fā)給哪個(gè)用戶,其實(shí)也可以后臺(tái)直接獲取用戶IP來(lái)判斷并推送
const socketUrl = 'ws://127.0.0.1:8868/websocket/' + info.username;
this.socket = new WebSocket(socketUrl);
// 監(jiān)聽socket打開
this.socket.onopen = function() {
console.log('瀏覽器WebSocket已打開');
};
// 監(jiān)聽socket消息接收
this.socket.onmessage = function(msg) {
// 轉(zhuǎn)換為json對(duì)象
const data = JSON.parse(msg.data);
that.$notify({
title: '建立連接',
// 這里也可以把返回信息加入到message中顯示
message: '實(shí)時(shí)報(bào)警服務(wù)連接成功,點(diǎn)擊查看報(bào)警信息詳情',
type: 'success',
duration: 0,
onClick: () => {
that.$router.push({
path: '/alarmManage/monitAlarmInfo'
});
}
})
};
// 監(jiān)聽socket錯(cuò)誤
this.socket.onerror = function() {
that.$notify({
title: '錯(cuò)誤',
message: '服務(wù)器錯(cuò)誤,無(wú)法接收實(shí)時(shí)報(bào)警信息',
type: 'error',
duration: 0
});
};
// 監(jiān)聽socket關(guān)閉
this.socket.onclose = function() {
console.log('WebSocket已關(guān)閉');
}
})
}
}
}