vue使用websocket的两种方式实例详解
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中为请求服务)
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()
}
当然,我们还有更方便快捷的在vue中使用websocket的方法,那就是使用GoEasy提供的websocket服务。
目前GoEasy提供完整的websocket前后端解决方案,简单的几行代码集成,即可快速搭建您的专属websocket服务。 同时支持各种前端技术框架如小程序、uniapp、vue,支持各种服务端语言如php、java、python等。对websocket有需求的开发者可以来注册试用一下【立即注册】