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)
}
}
},
}
}