欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue使用websocket的方法實(shí)例分析

 更新時(shí)間:2019年06月22日 11:05:32   作者:etemal_bright  
這篇文章主要介紹了vue使用websocket的方法,結(jié)合實(shí)例形式對(duì)比分析了vue.js使用websocket的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了vue使用websocket的方法。分享給大家供大家參考,具體如下:

最近項(xiàng)目需要使用到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請(qǐng)求過來的是string 需要格式
 if(demo.offsetHeight<demo1.offsetHeight){//內(nèi)部比外部高度大的時(shí)候滑動(dòng)
this.upScroll()//這是this指向websocket 所以沒有此方法 會(huì)報(bào)錯(cuò)
}
this.sliceArray() }
 }
 };
//連接關(guān)閉的回調(diào)方法 websocket.onclose = function () {
console.log("WebSocket連接關(guān)閉");
};
//連接發(fā)生錯(cuò)誤的回調(diào)方法 websocket.onerror = function () {
console.log("WebSocket連接發(fā)生錯(cuò)誤");
};
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。
 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 所以需要對(duì)websocket的方法賦值

希望本文所述對(duì)大家vue.js程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論