vue使用websocket的方法实例分析
2019-06-22 11:05
1671 查看
本文实例讲述了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程序设计有所帮助。
您可能感兴趣的文章:
相关文章推荐
- vue自定义指令的创建和使用方法实例分析
- go语言使用scp的方法实例分析
- PHP中静态变量的使用方法实例分析
- json2.js 入门教程之使用方法与实例分析
- ThinkPHP框架使用redirect实现页面重定向的方法实例分析
- Vue中使用方法、计算属性或观察者的方法实例详解
- vue计算属性的使用和vue实例的方法
- 实例分析vue循环列表动态数据的处理方法
- Sql Server事务语法及使用方法实例分析
- jQuery中DOM树操作之使用反向插入方法实例分析
- Vue1.0学习总结(3)———vue1.0的生命周期、vue计算属性computed的使用、vue实例(vm)上方法总结、vue结合动画使用
- go语言日志记录库简单使用方法实例分析
- jQuery中DOM树操作之使用反向插入方法实例分析
- vue实例中data使用return包裹的方法
- 在vue项目中优雅的使用SVG的方法实例详解
- Vue中使用webpack别名的方法实例详解
- jsp中Action使用session方法实例分析
- JavaScript使用shift方法移除素组第一个元素实例分析
- 使用 vue 实例更好的监听事件及vue实例的方法
- 实例分析编写vue组件方法