Vue+WebSocket頁面實(shí)時(shí)刷新長(zhǎng)連接的實(shí)現(xiàn)
最近vue項(xiàng)目要做數(shù)據(jù)實(shí)時(shí)刷新,折線圖每秒重畫一次,數(shù)據(jù)每0.5秒刷新一次,說白了就是實(shí)時(shí)刷新,因?yàn)閿?shù)據(jù)量較大,用定時(shí)器估計(jì)頁面停留一會(huì)就會(huì)卡死。。。
與后臺(tái)人員討論過后決定使用h5新增的WebSocket來實(shí)現(xiàn)數(shù)據(jù)實(shí)時(shí)展示,記錄一下過程以及碰到的問題;
注意:頁面刷新長(zhǎng)連接會(huì)被關(guān)閉,其實(shí)進(jìn)入當(dāng)前頁面建立長(zhǎng)連接的目的就是頁面不用F5刷新,所有數(shù)據(jù)自動(dòng)實(shí)時(shí)刷新,如果還是來回F5大刷頁面那就沒有意義了。。。
ps: 如果實(shí)在有這個(gè)需求的話,網(wǎng)上貌似有實(shí)現(xiàn)刷新頁面長(zhǎng)連接不斷的方法,請(qǐng)自行百度。。。。
<template> <div> </div></template><script> export default {data() { return {websock: null, }},created(){ //頁面剛進(jìn)入時(shí)開啟長(zhǎng)連接 this.initWebSocket() },destroyed: function() {//頁面銷毀時(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頁面實(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. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子3. 快速搭建Spring Boot+MyBatis的項(xiàng)目IDEA(附源碼下載)4. 基于PHP與XML的PDF文檔生成技術(shù)5. Python requests庫參數(shù)提交的注意事項(xiàng)總結(jié)6. php調(diào)用mysql存儲(chǔ)過程和函數(shù)的方法7. 教你在 IntelliJ IDEA 中使用 VIM插件的詳細(xì)教程8. AJAX的跨域問題解決方案9. js抽獎(jiǎng)轉(zhuǎn)盤實(shí)現(xiàn)方法分析10. 如何完全清理你的Docker數(shù)據(jù)
