首先需要与后台搭建连接
// vue3写法 如果是vue2 请把proxy换成this
const openWebScoket = () => {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
let socketUrl = `${hostWeb}/websocket/` + info.sc.uuid;
socketUrl = socketUrl
.replace("https", "wss")
.replace("http", "ws");
proxy.websocket = new WebSocket(socketUrl);
//打开事件
proxy.websocket.onopen = function (msg) {
console.log("开启scoket连接成功");
};
//获得消息事件
proxy.websocket.onmessage = function (msg) {
// msg是从后端拿的值 根据情况做一下数据处理
let res = JSON.parse(msg.data);
// 这里写你自己的业务逻辑
.....
}
//关闭事件
proxy.websocket.onclose = function (msg) {
console.log("websocket已关闭", msg);
};
//发生了错误事件
proxy.websocket.onerror = function (msg) {
console.log("websocket发生了错误", msg);
};
}
}
const getOK = (item) => {
if (typeof WebSocket == "undefined") {
ElMessage.warning("您的浏览器不支持WebSocket");
} else {
//哪里用到了websocket就在哪里调用,下面是后端需要的参数
proxy.websocket.send(
JSON.stringify({
uuid: info.sc.uuid,
type: 'openTemplate',
templateUrl: fileUrl
})
);
}
}
如果你使用的vue3,记得引入proxy
<script setup>
import { getCurrentInstance} from 'vue';
const { proxy } = getCurrentInstance();
</script>

本文展示了在Vue3中如何建立WebSocket连接,处理各种事件如开启、接收消息、关闭及错误,并提供了发送数据到后端的示例。同时提到了Vue2中使用代理的方式以及需要引入`getCurrentInstance`获取proxy。
4467

被折叠的 条评论
为什么被折叠?



