在vue中斩松,將下面的js export導出瞻凤,配置到main.js憨攒,如下
在main.Js中掛載
import {connectSocket} from './api/api' // 這里是webSocket的js文件
Vue.prototype.connectSocket = connectSocket;
頁面使用
this.connectSocket()
window.webSocket.onmessage = function (event) {
console.log(event)
this.list = event.data
}
webScoket連接代碼
<script>
window.onload = function(){
createWebSocket()
}
var lockReconnect = false; //避免重復連接
//判斷當前瀏覽器是否支持WebSocket
function createWebSocket() {
try {
if ('WebSocket' in window) {
var protocol = window.location.protocol;
var url = window.location.host + "/evo-websocket/evo-accesscontrol/websocket?keepalive_backend=websocket_evo_accesscontrol_backend"
if (protocol === 'http:') {
window.webSocket = new WebSocket("ws://" + url);
} else if (protocol === 'https:') {
window.webSocket = new WebSocket("wss://" + url);
}
websocketInit()
} else {
Message.error('你的瀏覽器不支持websocket,請切換瀏覽器阀参。');
}
} catch (e) {
websocketReconnect()
}
}
var timeId = null;
function websocketInit() {
//連接成功建立的回調(diào)方法
webSocket.onopen = function() {
console.log("webSocket連接成功");
webSocket.send('push-person-config');
timeId = setInterval(() => {
webSocket.send('push-person-config');
}, 30000)
};
webSocket.onclose = function(e) {
console.log("webSocket連接關閉");
websocketReconnect()
};
//每個頁面接收消息的處理方式都不同
webSocket.onerror = function() {
console.log("WebSocket連接發(fā)生錯誤");
};
webSocket.onmessage = function (event) {
console.log(JSON.parse(event.data))
var data = JSON.parse(event.data)
if (data.channelName === 'push-person-config') {
document.getElementById("personName").innerText = data.data.name
document.getElementById("personSex").innerText = data.data.sex
document.getElementById("personSell").innerText = data.data.department
document.getElementById("personImg").setAttribute('src', data.data.pictureUrl)
}
}
//監(jiān)聽窗口關閉事件肝集,當窗口關閉時,主動去關閉websocket連接蛛壳,防止連接還沒斷開就關閉窗口杏瞻,server端會拋異常所刀。
window.onbeforeunload = function() {
webSocket.close();
clearInterval(interval1)
clearInterval(interval2)
}
}
function websocketReconnect() {
if (lockReconnect) { // 是否已經(jīng)執(zhí)行重連
return;
}
lockReconnect = true;
//沒連接上會一直重連,設置延遲避免請求過多
timer && clearTimeout(timer);
var timer = setTimeout(function() {
createWebSocket()
lockReconnect = false;
}, 3000);
}
</script>