创建一个websocket组件
<script>
export default {
name: "index",
props: {
wsUrl: {
type: String,
require: true,
},
},
data() {
return {
socket: "",
};
},
watch: {
wsUrl: {
immediate: true,
handler() {
this.init();
},
},
},
methods: {
init() {
console.log(this.wsUrl, this.socket);
console.log("socket-begin");
if (this.wsUrl && this.wsUrl.trim() !== "") {
if (typeof WebSocket === "undefined") {
console.error("您的浏览器不支持socket");
this.$message({
message: "您的浏览器不支持socket",
type: "warning",
});
} else {
if (this.socket) {
this.socket.close();
}
this.socket = new WebSocket(this.wsUrl);
this.socket.onopen = this.open;
this.socket.onerror = this.error;
this.socket.onmessage = this.getMessage;
this.socket.onclose = this.close;
}
}
},
open() {
console.log("socket连接成功");
this.$emit("open");
},
error() {
console.log("连接错误");
this.$emit("error");
},
getMessage(msg) {
console.log(msg, msg.data);
this.$emit("getMessage", msg);
},
send(msg) {
if (this.socket) {
this.socket.send(msg);
} else {
console.error("socket is not exists");
}
},
close() {
if (this.socket) {
this.socket.close();
console.log("socket已经关闭");
this.$emit("close");
} else {
console.error("socket is not exists");
}
},
},
beforeDestroy() {
this.close();
},
};
</script>
在需要的组件中引用注册使用
<template>
<div class="view">
<!-- websocket连接 -->
<WebSocket :wsUrl="wsUrl" ref="WS" @open="open" @error="error" @getMessage="getMessage" @close="close" />
</div>
</template>
<script>
import WebSocket from "@/components/websocket";
export default {
components: {
WebSocket,
},
data() {
return {
wsUrl: "",
};
},
methods: {
reCallCopy(params) {
this.wsUrl = `ws://192.168.43.248:43504/backNotifySocket`;
},
getMessage(msg) {
if (msg.data === "WEBSOCKET_SESSION_CLOSE") {
this.$message({
message: `${this.tipsText}失败!`,
showClose: true,
type: "warning",
});
} else {
let resObj = JSON.parse(msg.data);
}
this.$refs.WS.close();
},
open() {
console.log("socket连接成功!");
},
error() {
console.log("-component-连接错误!");
this.$message({
message: `${this.tipsText}失败!`,
type: "warning",
showClose: true,
});
this.$refs.WS.close();
this.wsUrl = "";
this.$store.commit("publicModule/setViewLoading", false);
},
close() {
console.log("socket已经关闭,召测结束");
this.$store.commit("publicModule/setViewLoading", false);
},
},
};
</script>