websocket在vue中使用
方法一.组件中单独使用
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中为请求服务) import wesk from "./soketLink" class socket{ constructor(){ this.ws=null } WebSocketSet(par, Callback) { if (‘WebSocket‘ in window) { this.ws=wesk.wesk() // var ws = new WebSocket(`${axios.defaults.baseURL9}`); this.ws.onopen = (res => { console.log("socket连接成功") this.ws.send(par); }) this.ws.onmessage = (res => { let received_msg = JSON.parse(res.data); console.log("数据已接收...", received_msg); // this.newsList=received_msg; Callback(received_msg) }) } else { alert(‘当前浏览器 Not support websocket‘) } } close(){ this.ws.close() this.ws.onclose = (res => { console.log(console.log("socket已经关闭")) }) } } export default socket 2.在组件中引入websocket.js import socket from "../../../resource/websocket.js" data中定义websocket:null, mounted() { this.websocket=new socket() this.websocket.WebSocketSet(this.currentId,this.getSocketdata); }, methods中接收数据 //websocket返回数据 getSocketdata(res){ console.log(res,997788) this.newsList=res }, destroyed(){ //离开路由之后断开websocket连接 this.websocket.close() }