Vue+WebSocket頁(yè)面實(shí)時(shí)刷新長(zhǎng)連接的實(shí)現(xiàn)
最近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è)面銷(xiāo)毀時(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. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法5. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)8. jsp文件下載功能實(shí)現(xiàn)代碼9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲
