Vue3使用Websocket进行跨页面通信

安装

复制代码
npm i ws

安装vue3响应式库

复制代码
npm i @vue/reactivity

服务端创建连接--nodejs

javascript 复制代码
// Nodejs 端 index.js

// 引入 WebSocket 库
const WebSocket = require('ws');
// 引入 Vue 响应式 API
const reactivity = require('@vue/reactivity')

const {
    ref,
    computed,
    watch
} = reactivity

// 创建 WebSocket 服务器
const wss1 = new WebSocket.Server({
    port: 8001
});
const wss2 = new WebSocket.Server({
    port: 8002
});


// 记录数字
const count = ref(0)
// 计算出 10 倍
const sum = computed(() => 10 * count.value)

// 连接1
wss1.on('connection', (ws) => {
    // 处理来自客户端的消息
    ws.on('message', (message) => {
        // count 变化
        count.value = Number(String(message))
    });
    // 监听 count,并通知页面2
    watch(count, v => {
        ws.send(v)
    })
});

// 连接2
wss2.on('connection', (ws) => {
    // 处理来自客户端的消息
    ws.on('message', () => {
        // 执行清空命令
        count.value = 0
    });
    // 监听 sum,并通知页面2
    watch(sum, v => {
        ws.send(v)
    })

    // 模拟定时任务
    setTimeout(() => {
        ws.send(sum.value)
    }, 3600 * 12);
});

第一个页面连接8081--page1.vue

javascript 复制代码
<template>
  <div class="flex justify-center mb-3 text-4xl font-bold">页面1</div>
  <Button type="primary" @click="click">点击更新数据</Button>
  <div class="text-lg">当前数值:{{ count }}</div>
</template>

<script setup lang="ts">
import { Button } from 'ant-design-vue';
import { ref } from 'vue';

const count = ref(0);

// 创建 WebSocket 客户端
const socket = new WebSocket('ws://localhost:8001');

const click = () => {
  count.value++;
  // 发送消息到服务器
  socket.send(`${count.value}`);
};

// 接受服务端的消息
socket.addEventListener('message', e => {
  count.value = e.data;
});
</script>

第二个页面连接8082--page2.vue

javascript 复制代码
<template>
  <div class="flex justify-center mb-3 text-4xl font-bold">页面2</div>
  <Button type="primary" @click="click">清空数据</Button>
  <div class="text-lg">当前数值:{{ count }}</div>
</template>

<script setup lang="ts">
import { Button } from 'ant-design-vue';
import { ref } from 'vue';

const count = ref(0);

// 创建 WebSocket 客户端
const socket = new WebSocket('ws://localhost:8002');

const click = () => {
  // 发送消息到服务器
  socket.send('Hello, server!');
};

// 接受服务端的消息
socket.addEventListener('message', e => {
  count.value = e.data;
});
</script>
相关推荐
海拥✘3 小时前
深入理解 IP 地址:概念、分类与日常应用
网络·网络协议·tcp/ip
Miracle&4 小时前
1.TCP/IP模型:各层协议(重点TCP/UDP)
网络协议·tcp/ip·udp
Miracle&4 小时前
2.TCP深度解析:握手、挥手、状态机、流量与拥塞控制
linux·网络·tcp/ip
liulilittle4 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
c&0xff005 小时前
Flink反压问题
网络·flink
7ACE5 小时前
Wireshark TS | 接收数据超出接收窗口
网络协议·tcp/ip·wireshark
深圳多奥智能一卡(码、脸)通系统5 小时前
基于多奥(DAIC)品牌的IC卡电梯门禁系统(梯控)基础配置清单,整合核心硬件、软件及安全组件,确保系统可独立运行并支持未来扩展
网络
googleccsdn5 小时前
ESNP LAB 笔记:配置MPLS(Part4)
网络·笔记·网络协议
tan180°5 小时前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
Dontla6 小时前
Docker多共享网络配置策略(Docker多网络、Docker networks、Docker Compose网络、Docker网络、Docker共享网络)
网络·docker·容器