vue使用websocket的方法实例分析
本文实例讲述了vue使用websocket的方法。分享给大家供大家参考,具体如下:
最近项目需要使用到websocket但是框架是vue 网上查阅很多资料vue-websocket老是连接不上索性就不适用封装的插件了,直接使用原生的websocket 我这边需求是只需要接受就好不需要发送代码如下:
爬坑之路:vue里面this指向问题
第一版使用原生js
mounted(){
console.log(this)----------------------------------------------------------this指向vue
this.initWebpack();
},
methods:{
initWebpack(){
letwebsocket='';
if('WebSocket'inwindow){
websocket=newWebSocket("ws://192.168.1.99:8080/tv/websocket");
}else{
alert('当前浏览器Notsupportwebsocket')
}//连接成功建立的回调方法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
constwsuri="ws地址";
this.websock=newWebSocket(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程序设计有所帮助。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下