Vue3 使用 Vue-socket.io 实现实时通信

1.npm i  vue-socket.io --s

2.main.js 处理

import { createApp } from "vue";
import App from "./App.vue";

// 引入 ElementPlus
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import { registerSockets, destroySockets } from "./sockets";

// 引入 socket.io
import VueSocketIO from "vue-socket.io";

const app = createApp(App);

/* SocketIOClient.Socket, */
const socket = new VueSocketIO({
debug: false, // debug调试,生产建议关闭
connection: "http://localhost:3000",
});

// 便于在任意位置获取到 socket 对象
app.config.globalProperties.$socket = socket;
// 监听事件
app.config.globalProperties.$addSockets = registerSockets;
// 移除事件
app.config.globalProperties.$removeSockets = destroySockets;

app.use(ElementPlus).mount("#app");

3.sockets.js

export const registerSockets = (sockets, proxy) => {
sockets &&
Object.keys(sockets).forEach((t) => {
"subscribe" !== t &&
"unsubscribe" !== t &&
proxy.$socket.emitter.addListener(t, sockets[t], proxy);
});
};

export const destroySockets = (sockets, proxy) => {
sockets &&
Object.keys(sockets).forEach((t) => {
proxy.$socket.emitter.removeListener(t, proxy);
});
};

4.页面使用

<template>
<div> app </div>
</template>

<script>
import { getCurrentInstance, onMounted, onBeforeUnmount } from "vue";

export default {
components: { },
setup() {
const { proxy } = getCurrentInstance();

const sockets = {
welcome(data) {
console.log(data);
},
};

proxy.$socket.io.emit("send", "client send some data to node Serve.");

onMounted(() => {
proxy.$addSockets(sockets, proxy);
});

onBeforeUnmount(() => {
proxy.$removeSockets(sockets, proxy);
});

return {};
},
};
</script>
原文链接:https://blog.csdn.net/weixin_47746452/article/details/126827806

 

posted @   不再犯错  阅读(3773)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2017-01-06 jquery版固定边栏滚动特效
点击右上角即可分享
微信分享提示