首页 > 编程 > JavaScript > 正文

vue使用websocket的方法实例分析

2019-11-19 11:17:19
字体:
来源:转载
供稿:网友

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表