vue使用websocket的方法實例分析
本文實例講述了vue使用websocket的方法。分享給大家供大家參考,具體如下:
最近項目需要使用到websocket 但是框架是vue 網(wǎng)上查閱很多資料 vue-websocket 老是連接不上 索性就不適用封裝的插件了,直接使用原生的websocket 我這邊需求是 只需要接受就好 不需要發(fā)送 代碼如下:
爬坑之路:vue里面this指向問題
第一版 使用原生js
mounted(){ console.log(this)----------------------------------------------------------this指向vue this.initWebpack(); }, methods: { initWebpack() { let websocket = ''; if ('WebSocket' in window) { websocket = new WebSocket("ws://192.168.1.99:8080/tv/websocket"); } else { alert('當(dāng)前瀏覽器 Not support websocket') } //連接成功建立的回調(diào)方法 websocket.onopen = function () { console.log("WebSocket連接成功") console.log(this)----------------------------------------------------------this指向websocket }; //接收到消息的回調(diào)方法 websocket.onmessage = function (event) { console.log(this) console.log(event); this.productinfos=JSON.parse(event.data);//websocket請求過來的是string 需要格式 if(demo.offsetHeight<demo1.offsetHeight){//內(nèi)部比外部高度大的時候滑動 this.upScroll()//這是this指向websocket 所以沒有此方法 會報錯 } this.sliceArray() } } }; //連接關(guān)閉的回調(diào)方法 websocket.onclose = function () { console.log("WebSocket連接關(guān)閉"); }; //連接發(fā)生錯誤的回調(diào)方法 websocket.onerror = function () { console.log("WebSocket連接發(fā)生錯誤"); }; //監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會拋異常。 window.onbeforeunload = function () { websocket.close(); //關(guān)閉WebSocket連接 }; }, sliceArray(){//截取數(shù)組的后四位 }, upScroll(){ }, }
第二版:正解
methods:{ initWebpack(){//初始化websocket const wsuri = "ws地址"; this.websock = new WebSocket(wsuri);//這里面的this都指向vue this.websock.onopen = this.websocketopen; this.websock.onmessage = this.websocketonmessage; this.websock.onclose = this.websocketclose; this.websock.onerror = this.websocketerror; }, websocketopen(){//打開 console.log("WebSocket連接成功") }, websocketonmessage(e){ //數(shù)據(jù)接收 console.log(e) this.productinfos = JSON.parse(e.data); }, websocketclose(){ //關(guān)閉 console.log("WebSocket關(guān)閉"); }, websocketerror(){ //失敗 console.log("WebSocket連接失敗"); }, }
this.websock.onopen
的 this指向的是websocket 如果想要給vue里面的data里面的變量賦值 就需要 this
指向vue 所以需要對websocket的方法賦值
希望本文所述對大家vue.js程序設(shè)計有所幫助。
相關(guān)文章
Vue 實現(xiàn)CLI 3.0 + momentjs + lodash打包時優(yōu)化
今天小編就為大家分享一篇Vue 實現(xiàn)CLI 3.0 + momentjs + lodash打包時優(yōu)化,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11