本文實例講述了vue使用websocket的方法。分享給大家供大家參考,具體如下:
最近項目需要使用到websocket 但是框架是vue 網上查閱很多資料 vue-websocket 老是連接不上 索性就不適用封裝的插件了,直接使用原生的websocket 我這邊需求是 只需要接受就好 不需要發送 代碼如下:
爬坑之路: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('當前瀏覽器 Not support websocket') } //連接成功建立的回調方法 websocket.onopen = function () { console.log("WebSocket連接成功") console.log(this)----------------------------------------------------------this指向websocket };//接收到消息的回調方法websocket.onmessage = function (event) {console.log(this)console.log(event); this.productinfos=JSON.parse(event.data);//websocket請求過來的是string 需要格式 if(demo.offsetHeight<demo1.offsetHeight){//內部比外部高度大的時候滑動this.upScroll()//這是this指向websocket 所以沒有此方法 會報錯}this.sliceArray() } } };//連接關閉的回調方法 websocket.onclose = function () {console.log("WebSocket連接關閉");};//連接發生錯誤的回調方法 websocket.onerror = function () {console.log("WebSocket連接發生錯誤");};//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function () {websocket.close();//關閉WebSocket連接 }; },sliceArray(){//截取數組的后四位 }, 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){ //數據接收 console.log(e) this.productinfos = JSON.parse(e.data); }, websocketclose(){ //關閉 console.log("WebSocket關閉"); }, websocketerror(){ //失敗 console.log("WebSocket連接失敗"); },}this.websock.onopen 的 this指向的是websocket 如果想要給vue里面的data里面的變量賦值 就需要 this指向vue 所以需要對websocket的方法賦值
希望本文所述對大家vue.js程序設計有所幫助。
新聞熱點
疑難解答
圖片精選