export default {
name: 'Test',
data() {
return {
// websocket对象
ws: null,
// url
websocketURL: "ws://192.168.0.3"
}
},
methods: {
// 建立连接
handleConnect() {
const self = this;
self.ws = new WebSocket(self.websocketURL);
self.ws.onopen = function (event) {
console.log("连接开始");
}
self.ws.onmessage = function (event) {
let data = JSON.parse(event.data);
}
self.ws.onclose = function (event) {
console.log("连接关闭");
}
},
// 断开连接
handleExit() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
},
// 发送数据
handleSend(data) {
const self = this
if (self.ws) {
data = JSON.stringify(data)
console.log('data', data)
// 切换页面,websocket已断开,此时不能发送消息
if (self.ws.readyState === 1) {
self.ws.send(data)
}
}
},
}
}
05-05
1147
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-01
2754
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-14
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交