vue使用websocket有两种方式,一是组件中单独使用,二是封装公共方法 。具体的实现方式请看下文。
方法一、组件中单独使用
1.在methods中
WebSocketSet(){
if ('WebSocket' in window){
this.ws = new WebSocket(`${axios.defaults.baseURL9}`);
this.ws.onmessage = (res=>{
let received_msg= JSON.parse(res.data);
console.log("数据已接收...",received_msg);
this.newsList=received_msg;
})
this.ws.onopen=(res=>{
console.log("socket连接成功")
this.ws.send(this.currentId);
})
//......此处省略ws其他属性操作
}else{
alert('当前浏览器 Not support websocket')
}
},
2.在destroyed中关闭websocket
destroyed(){
this.ws.close();//离开路由之后断开websocket连接
}
方法二、封装公共方法
1.在src下创建文件夹存放websocket.js(soketLink中为请求服务)