国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue使用websocket的方法實例分析

2024-05-06 15:37:35
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 元谋县| 平湖市| 绥滨县| 抚远县| 崇礼县| 大英县| 济宁市| 南投市| 永安市| 应城市| 高碑店市| 商河县| 惠水县| 吴桥县| 乐亭县| 深水埗区| 施秉县| 余干县| 呼和浩特市| 屯留县| 珠海市| 定西市| 武穴市| 壤塘县| 桐城市| 汉阴县| 鲁山县| 大足县| 福海县| 宁波市| 永定县| 周口市| 阿合奇县| 马龙县| 德阳市| 新邵县| 乌兰浩特市| 鹤山市| 文昌市| 丽江市| 澄江县|