vue使用websocket的方法实例分析
前端  /  管理员 发布于 5年前   447
本文实例讲述了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第二版:正解
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中使用SockJS实现webSocket通信的过程
- Django+Vue实现WebSocket连接的示例代码
- vue + socket.io实现一个简易聊天室示例代码
- Vue与Node.js通过socket.io通信的示例代码
- socket io与vue-cli的结合使用的示例代码
- Vue Socket.io源码解读
- vue+socket.io+express+mongodb 实现简易多房间在线群聊示例
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
