zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Vue中websocket的使用方法

2023-02-18 16:35:59 时间

初始化WebSocket以及其他可能用到的方法

//初始化WebSocket
initWs() {
  if(typeOf(WebSocket) === "undefined") {
    //浏览器不支持WebSocket
    return false
  } else {
    this.socket = new WebSocket() //括号中填写后端提供的路径
    this.socket.onopen = this.open 
    this.socket.onerror = this.error
    this.socket.onmessage = this.getMessage
  }
},
//监听socket连接
open() {},
//监听socket连接
error() {},
//接收数据
getMessage(data) {}, //data为后端发过来的数据
//发送数据
send() {
  this.socket.send(data)
},
//监听socket连接关闭
close() {}

在data中初始化变量 mounted生命周期中调用初始化方法

data() {
  return {
    socket: ""
  }
},
mounted() {
  this.initWs()
},
destoryed() {
  this.socket.onclose = this.close
}

具体内容可参考如下链接WebSocket文档

解决WebSocket兼容性可参考如下链接解决WebSocket兼容性