Vue3利用Websocket举行跨页面通讯

[复制链接]
发表于 2026-1-24 17:45:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
安装
  1. npm i ws
复制代码
安装vue3相应式库
  1. npm i @vue/reactivity
复制代码
服务端创建毗连--nodejs
  1. // Nodejs 端 index.js
  2. // 引入 WebSocket 库
  3. const WebSocket = require('ws');
  4. // 引入 Vue 响应式 API
  5. const reactivity = require('@vue/reactivity')
  6. const {
  7.     ref,
  8.     computed,
  9.     watch
  10. } = reactivity
  11. // 创建 WebSocket 服务器
  12. const wss1 = new WebSocket.Server({
  13.     port: 8001
  14. });
  15. const wss2 = new WebSocket.Server({
  16.     port: 8002
  17. });
  18. // 记录数字
  19. const count = ref(0)
  20. // 计算出 10 倍
  21. const sum = computed(() => 10 * count.value)
  22. // 连接1
  23. wss1.on('connection', (ws) => {
  24.     // 处理来自客户端的消息
  25.     ws.on('message', (message) => {
  26.         // count 变化
  27.         count.value = Number(String(message))
  28.     });
  29.     // 监听 count,并通知页面2
  30.     watch(count, v => {
  31.         ws.send(v)
  32.     })
  33. });
  34. // 连接2
  35. wss2.on('connection', (ws) => {
  36.     // 处理来自客户端的消息
  37.     ws.on('message', () => {
  38.         // 执行清空命令
  39.         count.value = 0
  40.     });
  41.     // 监听 sum,并通知页面2
  42.     watch(sum, v => {
  43.         ws.send(v)
  44.     })
  45.     // 模拟定时任务
  46.     setTimeout(() => {
  47.         ws.send(sum.value)
  48.     }, 3600 * 12);
  49. });
复制代码
第一个页面毗连8081--page1.vue
  1. <template>
  2.   <div class="flex justify-center mb-3 text-4xl font-bold">页面1</div>
  3.   <Button type="primary" @click="click">点击更新数据</Button>
  4.   <div class="text-lg">当前数值:{{ count }}</div>
  5. </template>
  6. <script setup lang="ts">
  7. import { Button } from 'ant-design-vue';
  8. import { ref } from 'vue';
  9. const count = ref(0);
  10. // 创建 WebSocket 客户端
  11. const socket = new WebSocket('ws://localhost:8001');
  12. const click = () => {
  13.   count.value++;
  14.   // 发送消息到服务器
  15.   socket.send(`${count.value}`);
  16. };
  17. // 接受服务端的消息
  18. socket.addEventListener('message', e => {
  19.   count.value = e.data;
  20. });
  21. </script>
复制代码
第二个页面毗连8082--page2.vue
  1. <template>
  2.   <div class="flex justify-center mb-3 text-4xl font-bold">页面2</div>
  3.   <Button type="primary" @click="click">清空数据</Button>
  4.   <div class="text-lg">当前数值:{{ count }}</div>
  5. </template>
  6. <script setup lang="ts">
  7. import { Button } from 'ant-design-vue';
  8. import { ref } from 'vue';
  9. const count = ref(0);
  10. // 创建 WebSocket 客户端
  11. const socket = new WebSocket('ws://localhost:8002');
  12. const click = () => {
  13.   // 发送消息到服务器
  14.   socket.send('Hello, server!');
  15. };
  16. // 接受服务端的消息
  17. socket.addEventListener('message', e => {
  18.   count.value = e.data;
  19. });
  20. </script>
复制代码

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表