[Vue+WebSocket 實(shí)現(xiàn)頁(yè)面實(shí)時(shí)刷新長(zhǎng)連接]
*最近vue項(xiàng)目要做數(shù)據(jù)實(shí)時(shí)刷新,折線圖每秒重畫(huà)一次,數(shù)據(jù)每0.5秒刷新一次,說(shuō)白了就是實(shí)時(shí)刷新,因?yàn)閿?shù)據(jù)量較大,用定時(shí)器估計(jì)頁(yè)面停留一會(huì)就會(huì)卡死。。。
與后臺(tái)人員討論過(guò)后決定使用h5新增的WebSocket來(lái)實(shí)現(xiàn)數(shù)據(jù)實(shí)時(shí)展示,記錄一下過(guò)程以及碰到的問(wèn)題;
注意:頁(yè)面刷新長(zhǎng)連接會(huì)被關(guān)閉,其實(shí)進(jìn)入當(dāng)前頁(yè)面建立長(zhǎng)連接的目的就是頁(yè)面不用F5刷新,所有數(shù)據(jù)自動(dòng)實(shí)時(shí)刷新,如果還是來(lái)回F5大刷頁(yè)面那就沒(méi)有意義了。。。
ps: 如果實(shí)在有這個(gè)需求的話,網(wǎng)上貌似有實(shí)現(xiàn)刷新頁(yè)面長(zhǎng)連接不斷的方法,請(qǐng)自行百度。。。。
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {
websock: null,
}
},
created(){
//頁(yè)面剛進(jìn)入時(shí)開(kāi)啟長(zhǎng)連接
this.initWebSocket()
},
destroyed: function() {
//頁(yè)面銷毀時(shí)關(guān)閉長(zhǎng)連接
this.websocketclose();
},
methods: {
initWebSocket(){ //初始化weosocket
const wsuri = process.env.WS_API + "/websocket/threadsocket";//ws地址
this.websock = new WebSocket(wsuri);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
console.log("WebSocket連接成功");
},
websocketonerror(e) { //錯(cuò)誤
console.log("WebSocket連接發(fā)生錯(cuò)誤");
},
websocketonmessage(e){ //數(shù)據(jù)接收
const redata = JSON.parse(e.data);
//注意:長(zhǎng)連接我們是后臺(tái)直接1秒推送一條數(shù)據(jù),
//但是點(diǎn)擊某個(gè)列表時(shí),會(huì)發(fā)送給后臺(tái)一個(gè)標(biāo)識(shí),后臺(tái)根據(jù)此標(biāo)識(shí)返回相對(duì)應(yīng)的數(shù)據(jù),
//這個(gè)時(shí)候數(shù)據(jù)就只能從一個(gè)出口出,所以讓后臺(tái)加了一個(gè)鍵,例如鍵為1時(shí),是每隔1秒推送的數(shù)據(jù),為2
//時(shí)是發(fā)送標(biāo)識(shí)后再推送的數(shù)據(jù),以作區(qū)分
console.log(redata.value);
},
websocketsend(agentData){//數(shù)據(jù)發(fā)送
this.websock.send(agentData);
},
websocketclose(e){ //關(guān)閉
console.log("connection closed (" + e.code + ")");
},
},
}