在 Vue 3 项目中使用 MQTT 获取数据

在 Vue 3 项目中使用 MQTT 获取数据,需通过 MQTT.js 库实现与 MQTT 服务器的连接、订阅主题及消息处理。以下是分步指南:

一、初始化 Vue 3 项目

使用 Vue CLI 或 Vite 创建项目:

perl 复制代码
bash
1npm create vue@latest  # 使用 Vue CLI
2# 或
3npm create vite@latest my-vue3-mqtt -- --template vue

二、安装 MQTT.js 库

通过 npm 或 yarn 安装:

csharp 复制代码
bash
1npm install mqtt
2# 或
3yarn add mqtt

三、集成 MQTT 到 Vue 3 组件

1. 创建 MQTT 连接

在组件中引入 mqtt 并建立连接:

javascript 复制代码
javascript
1import { onMounted, onBeforeUnmount, ref } from 'vue';
2import mqtt from 'mqtt';
3
4export default {
5  setup() {
6    const client = ref(null);
7    const messages = ref([]);
8
9    const connectMqtt = () => {
10      const options = {
11        keepalive: 30,
12        clientId: `vue3_${Math.random().toString(16).slice(2)}`,
13        username: 'your_username', // 可选
14        password: 'your_password', // 可选
15        clean: true,
16      };
17
18      // 使用 WebSocket 协议(ws:// 或 wss://)
19      client.value = mqtt.connect('ws://your_mqtt_server:8083/mqtt', options);
20
21      client.value.on('connect', () => {
22        console.log('Connected to MQTT Broker');
23        // 订阅主题
24        client.value.subscribe('test/topic', { qos: 1 }, (err) => {
25          if (!err) console.log('Subscription successful');
26        });
27      });
28
29      client.value.on('message', (topic, message) => {
30        const data = JSON.parse(message.toString());
31        messages.value.push({ topic, data });
32        console.log(`Received: ${message.toString()} from ${topic}`);
33      });
34
35      client.value.on('error', (err) => {
36        console.error('MQTT Error:', err);
37      });
38
39      client.value.on('reconnect', () => {
40        console.log('Reconnecting...');
41      });
42
43      client.value.on('close', () => {
44        console.log('Disconnected from MQTT Broker');
45      });
46    };
47
48    onMounted(() => {
49      connectMqtt();
50    });
51
52    onBeforeUnmount(() => {
53      if (client.value) {
54        client.value.end();
55      }
56    });
57
58    return { messages };
59  }
60};

2. 发送消息(可选)

若需发布消息,可添加方法:

javascript 复制代码
javascript
1const publishMessage = (topic, payload) => {
2  if (client.value) {
3    client.value.publish(topic, JSON.stringify(payload), { qos: 1 }, (err) => {
4      if (err) console.error('Publish failed:', err);
5      else console.log('Message published');
6    });
7  }
8};

四、模板中显示消息

在组件模板中渲染接收到的消息:

xml 复制代码
html
1<template>
2  <div>
3    <h2>MQTT Messages</h2>
4    <ul>
5      <li v-for="(msg, index) in messages" :key="index">
6        <strong>{{ msg.topic }}:</strong> {{ msg.data }}
7      </li>
8    </ul>
9  </div>
10</template>

五、关键配置说明

  1. 连接协议:

    • 浏览器端必须使用 ws://(非加密)或 wss://(加密)协议。
    • 端口通常为 8083(ws)或 8084(wss),需与服务器配置一致。
  2. QoS 等级:

    • 0:至多一次(可能丢失)。
    • 1:至少一次(可能重复)。
    • 2:只有一次(确保到达)。
  3. 断线重连:

    • MQTT.js 默认自动重连,可通过 reconnectPeriod 调整重试间隔(毫秒)。
  4. 安全认证:

    • 若服务器启用认证,需在 options 中配置 username 和 password。

六、完整示例代码

xml 复制代码
javascript
1<script setup>
2import { ref, onMounted, onBeforeUnmount } from 'vue';
3import mqtt from 'mqtt';
4
5const client = ref(null);
6const messages = ref([]);
7
8const connectMqtt = () => {
9  const options = {
10    keepalive: 30,
11    clientId: `vue3_${Math.random().toString(16).slice(2)}`,
12    clean: true,
13  };
14
15  client.value = mqtt.connect('ws://your_mqtt_server:8083/mqtt', options);
16
17  client.value.on('connect', () => {
18    console.log('Connected');
19    client.value.subscribe('test/topic', { qos: 1 }, (err) => {
20      if (!err) console.log('Subscribed');
21    });
22  });
23
24  client.value.on('message', (topic, message) => {
25    messages.value.push({ topic, data: JSON.parse(message.toString()) });
26  });
27
28  client.value.on('error', (err) => {
29    console.error('Error:', err);
30  });
31};
32
33onMounted(() => {
34  connectMqtt();
35});
36
37onBeforeUnmount(() => {
38  if (client.value) client.value.end();
39});
40</script>
41
42<template>
43  <div>
44    <h2>MQTT Messages</h2>
45    <ul>
46      <li v-for="(msg, index) in messages" :key="index">
47        <strong>{{ msg.topic }}:</strong> {{ msg.data }}
48      </li>
49    </ul>
50  </div>
51</template>

七、常见问题解决

  1. 连接失败:

    • 检查服务器地址是否为 ws:// 或 wss://。
    • 确认端口和路径(如 /mqtt)是否正确。
  2. 消息乱码:

    • 使用 message.toString() 转换 Uint8Array 为字符串。
  3. 跨域问题:

    • 若服务器未配置 CORS,需通过代理或修改服务器配置解决。
  4. 性能优化:

    • 高频消息时,使用防抖或节流减少渲染次数。
    • 合并消息或使用 QoS 0 降低开销。
相关推荐
hunterandroid4 分钟前
HarmonyOS HUKS 密钥全生命周期实战:生成、轮换与失效处理
前端·华为
damoluomu6 分钟前
SSG 的后台怎么补:Node.js 生态里的三条路(番外二)
javascript·css·typescript·node.js·html
东鹏特饮13 分钟前
贪吃蛇小游戏html
前端·javascript·html
溪语流沙15 分钟前
【每天一个CSS | Day23】边框上有一道光在跑的流光呼吸卡片
前端·css
小马不起床17 分钟前
零基础玩转 FastAPI_10:前端登录、权限与布局
前端·状态模式·fastapi
程序员Sunday24 分钟前
JavaScript 深拷贝和浅拷贝有什么区别?structuredClone 能替代 JSON 拷贝吗?
前端·javascript
ShineWinsu1 小时前
对于CSS:选择器的解析
前端·css·面试·html·web·选择器·网页
m0_587383001 小时前
碰碰好评卡功能落地实战 从需求梳理到上线部署全流程实操指南
java·linux·服务器·前端·javascript·vue.js·人工智能
Pu_Nine_91 小时前
Vue‑Flow 从零入门实战|AI‑Agent 拓扑图开发
前端·javascript·vue.js
keyipatience1 小时前
CSS 学习(1):语法、引入方式、选择器、字体与背景
前端·css·html