vue3使用socket.io
1、安装
npm install vue-socket.io
2、创建socket.js文件
exportconstregisterSockets=(sockets, proxy)=>{
sockets &&
Object.keys(sockets).forEach((t)=>{// console.log(t);// "subscribe" !== t &&// "unsubscribe" !== t &&
proxy.$socket.emitter.addListener(t, sockets[t], proxy);});};exportconstdestroySockets=(sockets, proxy)=>{
sockets &&
Object.keys(sockets).forEach((t)=>{
proxy.$socket.emitter.removeListener(t, proxy);});};
3、 main.js使用
import VueSocketIO from'vue-socket.io';import{ registerSockets, destroySockets }from'./service/utils/sockets';const scUrl =import.meta.env.VITE_SOCKET_URL;const sockets =newVueSocketIO({debug:true,connection: scUrl,});
app.config.globalProperties.$socket = sockets;// 监听事件
app.config.globalProperties.$addSockets = registerSockets;// 移除事件
app.config.globalProperties.$removeSockets = destroySockets;
4、组件使用
const sockets ={//监听事件名deviceRealData(data){
console.log(data)},deviceRealAlarm(data){
console.log(data)}}onMounted(async()=>{
proxy.$addSockets(sockets, proxy);})onBeforeUnmount(()=>{
proxy.$removeSockets(sockets, proxy);});// 开启数据推送 发送事件functionopendata(){
proxy.$socket.io.emit('openRealData', state.currentData.deviceSn)
proxy.$socket.io.emit('openRealAlarm', state.currentData.deviceSn)}// 关闭数据推送functionstopData(){
proxy.$socket.io.emit('closeRealData')
proxy.$socket.io.emit('closeRealAlarm')}
原生websocket
let socket;/ Websoket连接成功事件
constwebsocketonopen=(res)=>{
console.log("WebSocket连接成功", res);};// Websoket接收消息事件constwebsocketonmessage=(res)=>{
console.log("接收消息", res);};// Websoket连接错误事件constwebsocketonerror=(res)=>{
console.log("连接错误", res);};// Websoket断开事件constwebsocketclose=(res)=>{
console.log("断开连接", res);};onMounted(()=>{const wsurl =import.meta.env.VITE_SOCKET_URL;
socket =newWebSocket(wsurl);
socket.onopen = websocketonopen;
socket.onmessage = websocketonmessage;
socket.onerror = websocketonerror;
socket.onclose = websocketclose;})onBeforeUnmount(()=>{// 关闭连接
socket.close();// 销毁 websocket 实例对象
socket =null;});//筛选器:提交functionhandleFilterSubmit(){//发送事件
socket.send(JSON.stringify({deviceSN:queryParams.value.input}))}
本文转载自: https://blog.csdn.net/weixin_46352558/article/details/134837170
版权归原作者 诺小D 所有, 如有侵权,请联系我们删除。
版权归原作者 诺小D 所有, 如有侵权,请联系我们删除。