vue使用websocket的方法实例分析

本文实例讲述了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程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。