Vue+WebSocket頁(yè)面實(shí)時(shí)刷新長(zhǎng)連接的實(shí)現(xiàn)
最近vue項(xiàng)目要做數(shù)據(jù)實(shí)時(shí)刷新,折線圖每秒重畫一次,數(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 + ')'); }, }, } </script>
到此這篇關(guān)于Vue+WebSocket頁(yè)面實(shí)時(shí)刷新長(zhǎng)連接的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Vue+WebSocket實(shí)時(shí)刷新長(zhǎng)連接內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. PHP字符串中提取文件名的實(shí)例方法2. React中的合成事件是什么原理3. myeclipse創(chuàng)建java項(xiàng)目的方法4. Vue Element前端應(yīng)用開(kāi)發(fā)之常規(guī)的JS處理函數(shù)5. Java Document生成和解析XML操作6. android studio xml文件實(shí)現(xiàn)添加注釋7. js與jquery獲取input輸入框中的值實(shí)例講解8. 利用PHP 7中的OPcache來(lái)實(shí)現(xiàn)Webshell9. python 將html轉(zhuǎn)換為pdf的幾種方法10. ASP.NET 2.0頁(yè)面框架的幾處變化
